小工具      在线工具  汉语词典  dos游戏  css  js  c++  java

mybatis注解开发

# MyBatis,mybatis,java 额外说明

收录于:23天前

基本的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映射文件 (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集成。

. . .

相关推荐

额外说明

讲解Git的基本概念和使用(InsCode AI创作助手)

Git 是一种分布式版本控制系统,它允许多个用户协同工作并对项目进行版本控制。下面是 Git 的基本概念和使用方式: 基本概念: 仓库(Repository):存储代码和版本历史记录的地方。 提交(Commit):在仓库中记录一次代码更改的操作。 分支(

额外说明

【JAVA-Day20】浅谈Java中的正则表达式的应用场景

标题 浅谈Java中的正则表达式的应用场景 摘要 引言 一、什么是正则表达式 1.1 验证手机号码格式是否正确 1.2 判断邮箱地址是否合法 1.3 从字符串中提取数字 1.4 替换特定文本 二、Java 中如何使用正则表达式 三、正则表达式的应用场景

额外说明

pyWeb开发基础——实现电商秒杀系统

实现电商秒杀系统 QQ 1285575001 Wechat M010527 技术交流 QQ群599020441 纪年科技aming # 功能实现 1.普通商城 用户模块 注册 登陆 修改资料 找回密码 数据 列表数据 数据详情 后台 管理用户 管理内容

额外说明

解读Linux常用命令使用方法

文章目录 1.前言 1.1 定义 1.2 特点 2.常用命令介绍 2.1 ls 2.2 pwd 2.3 cd 2.4 touch 2.5 cat 2.6 mkdir 2.7 rm 2.8 cp 2.9 mv 2.10 man(联机手册) 2.11 vim

额外说明

云计算安全:保护你的数据免受黑客侵害

文章目录 云计算的崛起 云计算安全的挑战 1. 数据隐私 2. 身份认证和访问控制 3. 网络安全 4. 云供应商安全 云计算安全的最佳实践 1. 数据加密 2. 强身份认证 3. 访问控制 4. 安全审计 5. 更新和漏洞管理 6. 培训和教育 云计算

额外说明

ch10.1 注意力机制的生物起源

文章参考,动手学深度学习; 10.1 生物学中的注意机制 10.1.1 影响注意力的 两种因素 人类的注意力会受到两种因素的影响: 非自主性提示: 通常是由外界的因素主导,比如基于环境中物体的突出性和易见性。 自主性提示: 收到人类自身意识的控制, 比如

额外说明

Python 07面向对象的三大特点【封装、继承、多态】

-前言 在软件开发的过程中,面向对象编程(Object-Oriented Programming,简称 OOP)已经成为了一种不可或缺的编程范式。它允许开发人员创建属于自己的对象,具有其特征和行为,通过将数据和方法绑定到一起来模拟现实世界中的对象。OOP

额外说明

解决Key columns should be a ordered prefix of the schema. KeyColumns[1] (starts from zero) is xxx, but

文章目录 1. 复现错误 2. 分析错误 3. 解决错误 1. 复现错误 今天在编写doris语句: CREATE TABLE IF NOT EXISTS test3.test ( `id` int COMMENT 'ID', `bb` stri

额外说明

Linux yum如何下载rpm包到本地

下载前先安装一个小插件 [root@wang yum.repos.d]# yum install -y yum-plugin-downloadonly 安装一个包的同时 加上 yum install yap --downloadonly --downl

额外说明

d3dx10_42.dll文件缺少的解决方法

其实很多用户玩单机游戏或者安装软件的时候就出现过这种问题,如果是新手第一时间会认为是软件或游戏出错了,其实并不是这样,其主要原因就是你电脑系统的该dll文件丢失了或者损坏了,这时你只需下载这个d3dx10_42.dll文件进行安装(前提是找到适合的版本)

ads via 小工具