介绍:
MyBatis 是支持普通 SQL查询,存储过程和高级映射的优秀持久层框架。MyBatis 消除了几乎所有的JDBC代码和参数的手工设置以及结果集的检索。MyBatis 使用简单的 XML或注解用于配置和原始映射,将接口和 Java 的POJOs(Plain Old Java Objects,普通的 Java对象)映射成数据库中的记录。
每个MyBatis应用程序主要都是使用SqlSessionFactory实例的,一个SqlSessionFactory实例可以通过SqlSessionFactoryBuilder获得。SqlSessionFactoryBuilder可以从一个xml配置文件或者一个预定义的配置类的实例获得
用xml文件构建SqlSessionFactory实例是非常简单的事情。推荐在这个配置中使用类路径资源(classpath resource),但你可以使用任何Reader实例,包括用文件路径或file://开头的url创建的实例。MyBatis有一个实用类----Resources,它有很多方法,可以方便地从类路径及其它位置加载资源。
maven管理
Mybatis:
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.0</version>
</dependency>
<!-- 添加mybatis与Spring整合的核心包 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.0</version>
</dependency>
还有Spring以及JUnit4单元测试的JAR包我就不在这里说明了
JAVA事例:
打开eclipse新建一个Maven Project项目
- 数据库及spring配置
在src/test/resources下新建database.properties文件,设置好数据库连接属性:
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/dome
jdbc.username=root
jdbc.password=admin123
然后添加spring配置文件applicationContext.xml 设置数据源及mybatis
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd">
<!--自动扫描该域名下的所有组件-->
<context:component-scan base-package="demo.core" />
<!-- 找到数据库配置文件 -->
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location">
<value>properties/database.properties</value>
</property>
</bean>
<!--获取数据库配置文件属性值,并建立数据库连接-->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</bean>
<!--实例化Mybatis SqlSessionFactory并设置数据源及自动扫描所有的mapping xml文件-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 实例化sqlSessionFactory时需要使用上述配置好的数据源以及SQL映射文件 -->
<property name="dataSource" ref="dataSource" />
<!-- 自动扫描me/gacl/mapping/目录下的所有SQL映射的xml文件,如果将name="mapperLocations" value可是设置为classpath:mapper/*.xml即扫描mapper文件下面的所有xml文件。 我这里是直接指向MyBatis-Configuration.xml文件,在该文件下对其所有xml进行管理-->
<property name="configLocation" value="classpath:mapper/config/MyBatis-Configuration.xml" />
</bean>
<!-- 配置扫描器 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 扫描demo.core.user.dao这个文件以及它的子文件下的所有映射接口类 -->
<property name="basePackage" value="demo.core.user.dao" />
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
</bean>
</beans>
在src/main/java下新建建立一个User实体类:
public class User {
private String username;
private String password;
private Boolean status;
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 Boolean getStatus() {
return status;
}
public void setStatus(Boolean status) {
this.status = status;
}
}
- 数据库映射文件配置
然后再在src/test/resources下新建添加一个UserMapper.xml文件,Mybatis是通过xml将实体类中的属性映射到数据中的字段。
<?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" >
<!--获取操作User数据源的dao文件-->
<mapper namespace="demo.core.user.dao.UserDao">
<!--resultMap以及resultType mybatis查询数据后返回的类型.resultType是直接的返回类型。这里我们定义一个数据返回类型resultMap其具体类型是User-->
<resultMap type="User" id="BaseResultMap">
<id column="id" property="id" jdbcType="INTEGER" />
<result column="username" property="username" jdbcType="VARCHAR" />
<result column="status" property="status" jdbcType="BIT" />
<result column="isDeleted" property="isdeleted" jdbcType="BIT" />
<result column="createTime" property="createtime" jdbcType="TIMESTAMP" />
<result column="modifyTime" property="modifytime" jdbcType="TIMESTAMP" />
</resultMap>
<!--定义一个公共返回字段-->
<sql id="Base_Column_List">
id, username, password, status, isDeleted, createTime,
modifyTime
</sql>
<!--添加一个selectByPrimaryKey方法(id就是方法名,必须和dao层的方法名一致)参数为integer类型,返回为id为BaseResultMap的外部resultMap类型,resultMap和resultType不能同时存在-->
<select id="selectByPrimaryKey" resultMap="BaseResultMap"
parameterType="java.lang.Integer">
select
<include refid="Base_Column_List" />
from user
where id = #{id,jdbcType=INTEGER}
</select>
</mapper>
如果select中返回类型参数定义的是resultType=”User”那么文件上面的<resultMap type="User" id="BaseResultMap">
定义可以删除,除非返回的User中包含其他对象并且返回的数据中该对象不为空,这种级联查询情况就必须使用resultMap作为返回类型,如果使用resultType会报错。具体会在mybatis级联查询事例中说明
mybatis运行时及数据库映射文件管理配置
在src/test/resources下建立MyBatis-Configuration.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>
<!--settings设置关系到mybatis运行时的行为方式,具体有哪些可以百度获取-->
<settings>
<!-- changes from the defaults -->
<setting name="lazyLoadingEnabled" value="false" />
<setting name="cacheEnabled" value="false" />
</settings>
<!--自动扫描type所指定的文件里面的所有实体,alias别名-->
<typeAliases>
<typeAlias type="demo.core.user.pojo.User" alias="User" />
<typeAlias type="demo.core.user.pojo.Model" alias="Model" />
<typeAlias type="demo.core.user.pojo.Role" alias="Role" />
<typeAlias type="demo.core.user.pojo.UserRoleKey" alias="UserRoleKey" />
</typeAliases>
<!--扫描配置的mapper.xml文件-->
<mappers>
<mapper resource="mapper/UserMapper.xml" />
<mapper resource="mapper/ModelMapper.xml" />
<mapper resource="mapper/RoleMapper.xml" />
</mappers>
</configuration>
JAVA代码
在src/main/java下建立一个UserDao接口文件,添加一个selectByPrimaryKey方法
public interface UserDao{
User selectByPrimaryKey(Integer id);
}
在src/main/java下建立一个UserService及实现该业务接口的UserServiceImpl类
public interface UserService{
//根据主键获取user
User findById(Integer id);
}
@Service("userService")
public class UserServiceImpl implements UserService{
@Autowired
UserDao userDao;
public User findById(Integer id){
return userDao.selectByPrimaryKey(id);
}
}
单元测试
在src/test/java下创建一个userTest类:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:spring/config/applicationContext.xml" })
@AutoTest(module = "user")
public class UserlTest {
@Autowired
public UserService userService;
@Test
public void test() {
User user= userService.findById(1);
System.out.println(user);
}
}