基本的mybatis做持久层开发三部分:mybatis-config.xml
、mapper映射
、spring-mybatis
。
mybatis-config.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">
<!-- XML 配置文件包含对 MyBatis 系统的核心设置 -->
<configuration>
<properties resource="db.properties" />
<settings>
<!-- 指定 MyBatis 所用日志的具体实现 -->
<setting name="logImpl" value="STDOUT_LOGGING"/>
<!-- 打开懒加载的开关 -->
<setting name="lazyLoadingEnabled" value="true"/>
<!-- 将积极加载改为消极加载 -->
<setting name="aggressiveLazyLoading" value="false"/>
</settings>
<!-- 定义别名 位置在setting之后 -->
<!-- <typeAliases> <typeAlias alias="user" type="org.model.User"></typeAlias> </typeAliases> -->
<!-- 别名定义 推荐这种方式 扫描该包中的实体类以及子包中的实体类-->
<typeAliases>
<package name="model"/>
</typeAliases>
<environments default="mysql">
<!-- 环境配置,即连接的数据库。 -->
<environment id="mysql">
<!-- 指定事务管理类型,type="JDBC"指直接简单使用了JDBC的提交和回滚设置 -->
<transactionManager type="JDBC" />
<!-- dataSource指数据源配置,POOLED是JDBC连接对象的数据源连接池的实现。 -->
<dataSource type="POOLED">
<property name="driver" value="${driver}" />
<property name="url" value="${url}" />
<property name="username" value="${username}" />
<property name="password" value="${password}" />
</dataSource>
</environment>
</environments>
<!-- mappers告诉了MyBatis去哪里找持久化类的映射文件 -->
<mappers>
<!-- <mapper resource="org/mapper/ten/proxy/UserMapper.xml"/> -->
<mapper class="Intefaceproxy.UserInterfaceMapper"/>
</mappers>
</configuration>
spring-mybatis.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<!--导入配置信息-->
<context:property-placeholder location="classpath:druid.properties"></context:property-placeholder>
<!--基于IoC容器创建数据源DataResource-->
<bean id="druidDataResource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="${druid.driver}"></property>
<property name="url" value="${druid.url}"></property>
<property name="username" value="${druid.username}"></property>
<property name="password" value="${druid.password}"></property>
<property name="initialSize" value="${druid.pool.init}"></property>
<property name="minIdle" value="${druid.pool.minIdle}"></property>
<property name="maxActive" value="${druid.pool.maxActive}"></property>
<property name="maxWait" value="${druid.pool.timeout}"></property>
</bean>
<!--赋值表达式会自动将导入的配置信息按名称赋给对应属性-->
<!--生产mybatis-spring提供的SqlSessionFactoryBean接收mybatis的SqlSessionFactory-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!--SqlSessionFactory中需要配置Mapper和DataResource-->
<property name="dataSource" ref="druidDataResource"></property>
<property name="mapperLocations" value="classpath:mapper/*.xml"></property>
<!--查询结果映射POJO,typeAliasesPackage使接口首字母小写为其id,通过id获取-->
<property name="typeAliasesPackage" value="cms.ssm.model"></property>
<!--加载mybatis-config.xml文件用于创建SqlSessionFactory-->
<property name="configLocation" value="classpath:mybatis-config.xml"></property>
</bean>
<!--扫描dao接口,并为其命名交由IoC容器管理,便于java代码中获取-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
<property name="basePackage" value="cms.ssm.dao"></property>
</bean>
<!--声明式事务事务管理,配置事务管理器-->
<bean class="org.springframework.jdbc.datasource.DataSourceTransactionManager" id="transactionManager">
<property name="dataSource" ref="druidDataResource"></property>
</bean>
<!--开启事务注解扫描-->
<tx:annotation-driven transaction-manager="transactionManager"></tx:annotation-driven>
</beans>
从mybatis3.4.0开始增加了@Mapper注解,以便不再编写mapper映射文件。
Mybatis中的注解基本上都在org.apache.ibatis.annotations目录下:
@MapperScan
该注解是Mybatis的注解,是为了集成Spring而写的注解。该注解主要是扫描某个包目录下的Mapper,将Mapper接口类交给Spring进行管理。使用需要导入mybatis-spring的工具包,且在spring环境下。该注解可以代替mybatis-config.xml的配置文件。
@映射器
该注解目的就是为了不再写mapper映射文件 (UserMapper.xml)。可以大大的简化编写xml的繁琐。仅仅代替了映射文件(UserMapper.xml)文件,SqlSessionFactory的构建过程任要有,也就是mybatis的配置文件不可省略。该注解是由Mybatis框架中定义的一个描述数据层接口的注解,注解往往起到的都是一个描述性作用,用于告诉Spring框架此接口的实现类由Mybatis负责创建,另外若是spring的环境,需要用@Repository
注解将其实现类对象注入到spring容器中。
sql语句映射
@插入:实现新增功能
@Insert("insert into user(id,name) values(#{id},#{name})")
public int insert(User user);
@选择:实现查询功能
@Select("Select * from user")
@Results({
@Result(id = true, column = "id", property = "id"),
@Result(column = "name", property = "name"),
@Result(column = "sex", property = "sex"),
@Result(column = "age", property = "age")
})
List<User> queryAllUser();
@SelectKey:插入后,获取id的值
以 MySQL 为例,MySQL 在插入一条数据后,使用 select last_insert_id() 可以获取到自增 id 的值。
@Insert("insert into user(id,name) values(#{id},#{name})")
@SelectKey(statement = "select last_insert_id()", keyProperty = "id", keyColumn = "id", resultType = int,before = false)
public int insert(User user);
@SelectKey 各个属性含义如下。
statement:表示要运行的 SQL 语句;
keyProperty:可选项,表示将查询结果赋值给代码中的哪个对象;
keyColumn:可选项,表示将查询结果赋值给数据表中的哪一列;
resultType:指定 SQL 语句的返回值;
before:默认值为 true,在执行插入语句之前,执行 select last_insert_id()。值为 flase,则在执行插入语句之后,执行 select last_insert_id()。
@插入:实现插入功能
@Insert("insert into user(name,sex,age) values(#{name},#{sex},#{age}")
int saveUser(User user);
@更新:实现更新功能
@Update("update user set name= #{name},sex = #{sex},age =#{age} where id = #{id}")
void updateUserById(User user);
@删除:实现删除功能
@Delete("delete from user where id =#{id}")
void deleteById(Integer id);
@参数:映射多个参数
@Param 用于在 Mapper 接口中映射多个参数。
int saveUser(@Param(value="user") User user,@Param("name") String name,@Param("age") Int age);
//@Param 中的 value 属性可省略,用于指定参数的别名。
结果集映射
@Result、@Results、@ResultMap 是结果集映射的三大注解。
结果集映射关系声明代码:
@Select({
"select id, name, class_id from student"})
@Results(id="studentMap", value={
@Result(column="id", property="id", jdbcType=JdbcType.INTEGER, id=true),
@Result(column="name", property="name", jdbcType=JdbcType.VARCHAR),
@Result(column="class_id ", property="classId", jdbcType=JdbcType.INTEGER)
})
List<Student> selectAll();
下面为 @Results 各个属性的含义。
id:表示当前结果集声明的唯一标识;
value:表示结果集映射关系;
@Result:代表一个字段的映射关系。其中,column 指定数据库字段的名称,property 指定实体类属性的名称,jdbcType 数据库字段类型,id 为 true 表示主键,默认 false。
可以使用@ResultMap引用映射的结果集,其中value可以省略。
@Select({
"select id, name, class_id from student where id = #{id}"})
@ResultMap(value="studentMap")
Student selectById(Integer id);
这样就无需在每次声明结果集映射时复制冗余代码,从而简化了开发并提高了代码的可重用性。
关系映射
@一:用于一对一关系映射
@Select("select * from student")
@Results({
@Result(id=true,property="id",column="id"),
@Result(property="name",column="name"),
@Result(property="age",column="age"),
@Result(property="address",column="address_id",one=@One(select="net.biancheng.mapper.AddressMapper.getAddress"))
})
public List<Student> getAllStudents();
@许多:用于一对多关系映射
@Select("select * from t_class where id=#{id}")
@Results({
@Result(id=true,column="id",property="id"),
@Result(column="class_name",property="className"),
@Result(property="students", column="id", many=@Many(select="net.biancheng.mapper.StudentMapper.getStudentsByClassId"))
})
public Class getClass(int id);
其他注意事项
参考
注解 | 对应xml | 影响 |
---|---|---|
@Cache命名空间 | <cache> |
为给定的命名空间(例如类)配置缓存。属性:实现、驱逐、flushInterval、大小和读写。 |
@CacheNamespaceRef | <cacheRef> |
参考另一个命名空间中的缓存来使用它。属性:值,应该是命名空间的字符串值(即类的完全限定名称)。 |
@ConstructorArgs | <constructor> |
收集一组结果并将它们传递给被抢对象的构造函数。属性:值,是形参数组。 |
@Arg | <arg>,<idArg> |
单独的构造函数参数,它们是 ConstructorArgs 集合的一部分。属性:id、column、javaType、typeHandler。 id 属性是一个布尔值,用于标识用于比较的属性,类似于 XML 元素。 |
@类型鉴别器 | <discriminator> |
一组实例值用于确定结果映射的行为。属性:column、javaType、jdbcType、typeHandler、cases。 Cases 属性是实例数组。 |
@案件 | <case> |
单个实例的值及其对应的映射。属性:值、类型、结果。 Results 属性是结果数组,因此此注释与实际的 ResultMap 非常相似,由下面的 Results 注释指定。 |
@结果 | <resultMap> |
结果映射列表,包含特定结果列如何映射到属性或字段的详细信息。属性:值、id。 value 属性是结果注释的数组。 |
@结果 | <result> |
列与属性或字段之间的单独结果映射。属性:id、column、property、javaType、jdbcType、type Handler、一、多。 |
@选项 | 映射语句属性 | 此注释提供了对交换和配置选项的广泛访问,这些选项通常作为属性出现在映射语句上。选项注释提供了一种连贯且清晰的访问它们的方法,而不是使每个语句注释变得复杂。属性:useCache=true、flushCache=FlushCachePolicy.DEFAULT、resultSetType=FORWARD_ONLY、statementType=PREPARED、fetchSize=-1、timeout=-1 useGenerateKeys=false、keyProperty=”id”、keyColumn=””、resultSets=””。了解 Java 注释非常重要,因为无法将“null”指定为值。因此,一旦使用Options注释,该语句就受所有默认值的约束。请注意使用什么默认值以避免不良行为。 |
@插入 | <insert> |
轻微地 |
@更新 | <update> |
轻微地 |
@删除 | <delete> |
轻微地 |
@选择 | <select> |
轻微地 |
@InsertProvider | <insert> |
根据执行的映射语句,MyBatis 将实例化该类,然后执行提供者指定的方法。该方法可以选择接受参数对象来构建动态 SQL |
@UpdateProvider | <update> |
与上面相同 |
@DeleteProvider | <delete> |
与上面相同 |
@SelectProvider | <select> |
与上面相同 |
@参数 | 不适用 | 如果您的映射器的方法需要多个参数,则可以将此注释应用于映射器的方法参数,为每个参数指定一个名称。否则,多个参数将根据其顺序位置命名(不包括任何 RowBounds 参数),例如#{param1}、#{param2}等,这是默认的。使用@Param("person"),参数应命名为#{person}。 |
@一 | 不适用 | 复杂类型的各个属性值的映射。属性:select,可以加载适当类型实例的映射语句(即映射器方法)的完全限定名称 |
@许多 | 不适用 | 类似于@One,一对多关系 |
@SelectKey | 不适用 | 获取最新的插入id。 |
大多数注释在 xml 映射文件中都有相应的元素,但并非全部。另外,mybatis-spring中提供了@Mapper注解和@MapperScan注解,用于与spring集成。