内容简介:MyBatis学习(一)
什么是 MyBatis ?
官方解释:MyBatis 是支持定制化 SQL 、存储过程以及高级映射的优秀的持久层框架。MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集。MyBatis 可以对配置和原生Map使用简单的 XML 或注解,将接口和 Java 的 POJOs(Plain Old Java Objects,普通的 Java对象)映射成数据库中的记录。
MyBatis结构图:
MyBatis通过配置和注解简化JDBC的操作,了解MyBatis,首先要了解他的配置信息,XML配置映射文件中,最重要的是设置(settings)和属性(properties)信息。
properties
设置属性信息,设置连接数据库:
<properties resource="org/mybatis/example/config.properties"> <property name="driver" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/wendao? useUnicode=true&characterEncoding=utf8"/> <property name="username" value="root"/> <property name="password" value="root"/> </properties>
配置数据库的连接有多种方法:
1,在config.properties的属性文件中配置
2,如上,在XML配置文件中配置
3,在Java类中配置,通过方法参数传递属性
同时,也可以灵活的结合这三种配置方法进行数据库的配置,重复配置信息时有些配置信息就会被覆盖掉,这三种方法有个优先级的问题,高优先级的会覆盖掉低优先级的。
如果属性在不只一个地方进行了配置,那么 MyBatis 将按照下面的顺序来加载:
1,在 properties 元素体内指定的属性首先被读取。
2,然后根据 properties 元素中的 resource 属性读取类路径下属性文件或根据 url 属性指定的路径读取属性文件,并覆盖已读取的同名属性。
3,最后读取作为方法参数传递的属性,并覆盖已读取的同名属性。
也就是说:方法参数传递的属性>resource/url中配置的属性> properties 中设置的属性
settings
设置属性参数,这些参数会改变 MyBatis 的运行时行为。
一个配置完整的 settings 元素的示例如下:
<!– 配置设置 –>
<settings>
<!– 配置全局性 cache 的 ( 开 / 关) default:true –>
<setting name=“cacheEnabled” value=“true”/>
<!– 是否使用 懒加载 关联对象 同 hibernate中的延迟加载 一样 default:true ,当开启时,所有关联对象都会延迟加载。 特定关联关系中可通过设置fetchType属性来覆盖该项的开关状态–>
<setting name=“lazyLoadingEnabled” value=“true”/>
<!– [当对象使用延迟加载时 属性的加载取决于能被引用到的那些延迟属性,否则,按需加载(需要的是时候才去加载)] –>
<setting name=“aggressiveLazyLoading” value=“true”/>
<!– 是否允许单条sql 返回多个数据集 (取决于驱动的兼容性) default:true –>
<setting name=“multipleResultSetsEnabled” value=“true”/>
<!– 是否可以使用列的别名 (取决于驱动的兼容性) default:true–>
<setting name=“useColumnLabel” value=“true”/>
<!–允许JDBC 生成主键。需要驱动器支持。如果设为了true,这个设置将强制使用被生成的主键,有一些驱动器不兼容不过仍然可以执行。 default:false–>
<setting name=“useGeneratedKeys” value=“false”/>
<!–指定 MyBatis 如何自动映射 数据基表的列
NONE:不隐射 PARTIAL:部分 FULL:全部–>
<setting name=“autoMappingBehavior” value=“PARTIAL”/>
<!– 这是默认的执行类型
SIMPLE :简单
REUSE:执行器可能重复使用prepared statements 语句
BATCH:执行器可以重复执行语句和批量更新 –>
<setting name=“defaultExecutorType” value=“SIMPLE”/>
<!– 设置驱动等待数据响应的超时数 默认没有设置–>
<setting name=“defaultStatementTimeout” value=“25000″/>
<!– [是否启用 行内嵌套语句 defaut:false] –>
<setting name=“safeRowBoundsEnabled” value=“false”/>
<!– [是否 启用 数据中 A_column 自动映射 到 Java类中驼峰命名的属性 default:fasle] –>
<setting name=“mapUnderscoreToCamelCase” value=“false”/>
<!– 设置本地缓存范围 session:就会有数据的共享 statement:语句范围 (这样就不会有数据的共享 ) defalut:session –>
<setting name=“localCacheScope” value=“SESSION”/>
<!– 设置但JDBC类型为空时,某些驱动程序 要指定值,default:OTHER –>
<setting name=“jdbcTypeForNull” value=“DEFAULT”/>
<!– 设置触发延迟加载的方法 –>
<setting name=“lazyLoadTriggerMethods” value=“equals,clone,hashCode,toString”/>
</settings>
大概了解了MyBatis的配置信息,接下来通过一个增删改查的Demo来系统的了解一下MyBatis的流程吧。
新建一个Java工程,上图是大体结构:
sqlMapConfig.xml配置信息:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!-- 加载属性文件 -->
<properties resource="db.properties"></properties>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC" />
<!-- 数据库连接池-->
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driver}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="org/mybatis/pojo/UserInfo.xml"></mapper>
</mappers>
</configuration>
POJO类:
package org.mybatis.pojo;
public class UserInfo {
private int id;
private String username;
private String password;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public UserInfo() {
super();
// TODO Auto-generated constructor stub
}
public UserInfo(Integer id, String username, String password) {
super();
this.id = id;
this.username = username;
this.password = password;
}
}
POJO映射文件:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="mybatis_example">
<select id="findUserInfo" parameterType="int" resultType="org.mybatis.pojo.UserInfo">
select * from user_info where id = #{id}
</select>
<insert id="addUser" parameterType="org.mybatis.pojo.UserInfo">
insert into user_info(username,password) value (#{username},#{password})
</insert>
<delete id="delUser" parameterType="org.mybatis.pojo.UserInfo">
delete from user_info where id = #{value}
</delete>
<update id="updUser" parameterType="org.mybatis.pojo.UserInfo">
update user_info set username=#{username},password=#{password} where id=#{id}
</update>
</mapper>
接下来是测试类,使用单元测试:
package org.mybatis.example;
import java.io.IOException;
import java.io.InputStream;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;
import org.mybatis.pojo.UserInfo;
public class MyBatisExample {
// 查询
@Test
public void findUserInfo() throws IOException{
String resource = "sqlMapConfig.xml";
InputStream input = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(input);
SqlSession sqlsession = sqlSessionFactory.openSession();
//第一个参数:映射文件的id,
//第二个参数:指定和映射文件parameterType所匹配的参数
UserInfo user = sqlsession.selectOne("mybatis_example.findUserInfo",1);
System.out.println("用户名是:"+user.getUsername());
}
// 新增
@Test
public void addUser() throws IOException{
String resource = "sqlMapConfig.xml";
InputStream input = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(input);
SqlSession sqlsession = sqlSessionFactory.openSession();
String name = "赵敏";
String pass = "123";
UserInfo ui = new UserInfo();
ui.setUsername(name);
ui.setPassword(pass);
sqlsession.insert("mybatis_example.addUser",ui);
sqlsession.commit();
sqlsession.close();
}
// 删除
@Test
public void delUser() throws IOException{
String resource = "sqlMapConfig.xml";
InputStream input = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(input);
SqlSession sqlsession = sqlSessionFactory.openSession();
sqlsession.delete("mybatis_example.delUser",1);
sqlsession.commit();
sqlsession.close();
}
// 修改
@Test
public void updUser() throws IOException{
String resource = "sqlMapConfig.xml";
InputStream input = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(input);
SqlSession sqlsession = sqlSessionFactory.openSession();
String name = "张无忌";
String pass = "123";
UserInfo ui = new UserInfo();
ui.setId(2);
ui.setUsername(name);
ui.setPassword(pass);
sqlsession.update("mybatis_example.updUser",ui);
sqlsession.commit();
sqlsession.close();
}
}
代码中的名词解释:
parameterType:MyBatis中通过parameterType指定输入的参数类型
resultType:MyBatis中通过resultType指定输出的结果
#{}:表示的是占位符,#{}接收的参数是输入的参数,类型可以是简单类型、pojo、hashmap
#{}如果接收的是简单类型的话,里面的值可以value或者其他名称
#{}接收pojo对象,通过OGNL读取对象中的属性值,通过属性.属性的方式获取。
selectOne:表示查询出一条记录,如果是使用selectone是可以实现的结果,selectList也是可以实现了(list中只有一个对象)
selectList: 表示查询出一个列表(多条记录)进行映射的。如果是使用selectOne是不可以实现的。
MyBatis和Hibernate都是最常用的持久层框架,很多学习MyBatis框架的人都对Hibernate框架也有一定的了解,对比他们的异同可以更快速的上手MyBatis,关于两个框架的比较:
以上所述就是小编给大家介绍的《MyBatis学习(一)》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!
猜你喜欢:- 一文读懂监督学习、无监督学习、半监督学习、强化学习这四种深度学习方式
- 学习:人工智能-机器学习-深度学习概念的区别
- 统计学习,机器学习与深度学习概念的关联与区别
- 混合学习环境下基于学习行为数据的学习预警系统设计与实现
- 学习如何学习
- 深度学习的学习历程
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Mobilizing Web Sites
Layon, Kristofer / 2011-12 / 266.00元
Everyone has been talking about the mobile web in recent years, and more of us are browsing the web on smartphones and similar devices than ever before. But most of what we are viewing has not yet bee......一起来看看 《Mobilizing Web Sites》 这本书的介绍吧!