mybatis注解开发

得意时要看淡,失意时要看开。不论得意失意,切莫大意;不论成功失败,切莫止步。志得意满时,需要的是淡然,给自己留一条退路;失意落魄时,需要的是泰然,给自己觅一条出路mybatis注解开发,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com,来源:原文

基本的mybatis做持久层开发三部分:mybatis-config.xmlmapper映射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
该注解目的就是为了不再写mapper映射文件 (UserMapper.xml)。可以大大的简化编写xml的繁琐。仅仅代替了映射文件(UserMapper.xml)文件,SqlSessionFactory的构建过程任要有,也就是mybatis的配置文件不可省略。该注解是由Mybatis框架中定义的一个描述数据层接口的注解,注解往往起到的都是一个描述性作用,用于告诉Spring框架此接口的实现类由Mybatis负责创建,另外若是spring的环境,需要用@Repository注解将其实现类对象注入到spring容器中。

sql语句映射
@Insert:实现新增功能

@Insert("insert into user(id,name) values(#{id},#{name})")
public int insert(User user);

@Select:实现查询功能

@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("insert into user(name,sex,age) values(#{name},#{sex},#{age}")
int saveUser(User user);

@Update:实现更新功能

@Update("update user set name= #{name},sex = #{sex},age =#{age} where id = #{id}")
void updateUserById(User user);

@Delete:实现删除功能

@Delete("delete from  user  where id =#{id}")
void deleteById(Integer id);

@Param:映射多个参数

@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);

这样不需要每次声明结果集映射时都复制冗余代码,简化开发,提高了代码的复用性。

关系映射

@one:用于一对一关系映射

@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();  

@many:用于一对多关系映射

@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 作用
@CacheNamespace <cache> 为给定的命名空间 (比如类) 配置缓存。 属性:implemetation,eviction, flushInterval,size 和 readWrite。
@CacheNamespaceRef <cacheRef> 参照另外一个命名空间的缓存来使用。 属性:value,应该是一个名空间的字 符串值(也就是类的完全限定名) 。
@ConstructorArgs <constructor> 收集一组结果传递给一个劫夺对象的 构造方法。属性:value,是形式参数 的数组。
@Arg <arg>,<idArg> 单 独 的 构 造 方 法 参 数 , 是 ConstructorArgs 集合的一部分。属性: id,column,javaType,typeHandler。 id 属性是布尔值, 来标识用于比较的属 性,和XML 元素相似。
@TypeDiscriminator <discriminator> 一组实例值被用来决定结果映射的表 现。 属性: column, javaType, jdbcType, typeHandler,cases。cases 属性就是实 例的数组。
@Case <case> 单独实例的值和它对应的映射。属性: value,type,results。Results 属性是结 果数组,因此这个注解和实际的 ResultMap 很相似,由下面的 Results 注解指定。
@Results <resultMap> 结果映射的列表, 包含了一个特别结果 列如何被映射到属性或字段的详情。 属 性:value, id。value 属性是 Result 注解的数组。
@Result <result> 在列和属性或字段之间的单独结果映 射。属 性:id,column, property, javaType ,jdbcType ,type Handler, one,many。
@Option 映射语句的属性 这个注解提供访问交换和配置选项的 宽广范围, 它们通常在映射语句上作为 属性出现。 而不是将每条语句注解变复 杂,Options 注解提供连贯清晰的方式 来访问它们。属性:useCache=true , flushCache=FlushCachePolicy.DEFAULT , resultSetType=FORWARD_ONLY , statementType=PREPARED , fetchSize=-1 , , timeout=-1 useGeneratedKeys=false , keyProperty=”id” , keyColumn=”” , resultSets=””。 理解 Java 注解是很 重要的,因为没有办法来指定“null” 作为值。因此,一旦你使用了 Options 注解,语句就受所有默认值的支配。要 注意什么样的默认值来避免不期望的 行为。
@Insert <insert>
@Update <update>
@Delete <delete>
@Select <select>
@InsertProvider <insert> 基于执行的映射语句, MyBatis 会实例化这个类,然后执行由 provider 指定的方法. 该方法可以有选择地接受参数对象,用于来构建动态 SQL
@UpdateProvider <update> 同上
@DeleteProvider <delete> 同上
@SelectProvider <select> 同上
@Param N/A 如果你的映射器的方法需要多个参数, 这个注解可以被应用于映射器的方法 参数来给每个参数一个名字。否则,多 参数将会以它们的顺序位置来被命名 (不包括任何 RowBounds 参数) 比如。 #{param1} , #{param2} 等 , 这 是 默 认 的 。 使 用 @Param(“person”),参数应该被命名为 #{person}。
@One N/A 复杂类型的单独属性值映射。属性: select,已映射语句(也就是映射器方 法)的完全限定名,它可以加载合适类 型的实例
@Many N/A 与@One类似,一对多的关系
@SelectKey N/A 获取最新插入id。

绝大部分注解,在xml映射文件中都有元素与之对应,但是不是所有。此外在mybatis-spring中提供了@Mapper注解和@MapperScan注解,用于和spring进行整合。

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/156265.html

(0)
飞熊的头像飞熊bm

相关推荐

发表回复

登录后才能评论
极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!