Mybatis之配置文件和注解CRUD

目录

1 Mybatis配置文件

1.1 Mybatis配置文件conf.xml

1.1.1 配置单独放在一个properties文件

1.1.2 settings

1.1.3 typeAliases

1.1.4 mappers

1.2 sql映射文件userMapper.xml

1.3 配置测试

2 使用MyBatis对表执行CRUD操作——基于注解的实现

2.1 mapper接口

2.2 配置conf.xml

2.3 测试类


1 Mybatis配置文件

 用到的实体user

 public class User {
 
     //实体类的属性和表的字段名称一一对应
    private int id;
     private String name;
     private int age;

    省去getset方法
}

1.1 Mybatis配置文件conf.xml

mybatis-config.xml的配置内容和顺序如下(顺序不能乱):

  • properties(属性)用于配置属性信息
  • settings(全局参数设置)用于配置MyBatis的运行时方式
  • typeAliases(类型别名)配置类型别名,可以在xml中用别名取代全限定名
  • typeHandlers(类型处理器)配置类型处理器
  • objectFactory(对象工厂)
  • plugins(插件)配置拦截器,用于拦截sql语句的执行
  • environments(环境信息集合)
    environment(单个环境信息)配置数据源信息、连接池、事务属性等
  • transactionManager(事务)
  • dataSource(数据源)
  • mappers(映射器)配置SQL映射文件

在src目录下创建一个conf.xml文件,如下图所示:

1.1.1 配置单独放在一个properties文件

其中db.properties

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis
name=root
password=root

在MyBatis的conf.xml文件中引用db.properties文件

<?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>

<!-- 引用db.properties配置文件 -->
<properties resource="db.properties"/>
<!--
 development : 开发模式
work : 工作模式
-->
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<!-- 配置数据库连接信息 -->
<dataSource type="POOLED">
<!-- value属性值引用db.properties配置文件中配置的值 -->
<property name="driver" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${name}"/>
<property name="password" value="${password}"/>
</dataSource>
</environment>
</environments>

</configuration>

1.1.2 settings

mybatis全局配置参数,全局参数将会影响mybatis的运行行为

配置格式:

<settings>
    <setting name="name1" value="value1" />
    <setting name="name2" value="value2" />
    <setting name="name3" value="value3" />
    ......
    <setting name="nameN" value="valueN" />
</settings>

setting可设置的项相关介绍参见下表:

设置参数

描述

有效值

默认值

cacheEnabled

这个配置使全局的映射器启用或禁用缓存

true | false

true

lazyLoadingEnabled

全局启用或禁用延迟加载。当禁用时, 所有关联对象都会即时加载。

true | false

false

aggressiveLazyLoading

当启用时, 有延迟加载属性的对象在被 调用时将会完全加载任意属性。否则,每种属性将会按需要加载。

true | false

true

multipleResultSetsEnabled

允许或不允许多种结果集从一个单独 的语句中返回(需要适合的驱动)

true | false

true

useColumnLabel

使用列标签代替列名。 不同的驱动在这 方便表现不同。 参考驱动文档或充分测 试两种方法来决定所使用的驱动。

true | false

true

useGeneratedKeys

允许 JDBC 支持生成的键。 需要适合的 驱动。 如果设置为 true 则这个设置强制生成的键被使用, 尽管一些驱动拒绝兼 容但仍然有效(比如 Derby)

true | false

False

autoMappingBehavior

指定 MyBatis 如何自动映射列到字段/ 属性。PARTIAL 只会自动映射简单, 没有嵌套的结果。FULL 会自动映射任 意复杂的结果(嵌套的或其他情况) 。

NONE, PARTIAL, FULL

PARTIAL

defaultExecutorType

配置默认的执行器。SIMPLE 执行器没 有什么特别之处。REUSE 执行器重用 预处理语句。BATCH 执行器重用语句 和批量更新

SIMPLE REUSE BATCH

SIMPLE

defaultStatementTimeout

设置超时时间, 它决定驱动等待一个数 据库响应的时间。

Any positive integer

Not Set (null)

safeRowBoundsEnabled

Allows using RowBounds on nested statements.

true | false

False

mapUnderscoreToCamelCase

Enables automatic mapping from classic database column names A_COLUMN to camel case classic Java property names aColumn.

true | false

False

localCacheScope

MyBatis uses local cache to prevent circular references and speed up repeated nested queries. By default (SESSION) all queries executed during a session are cached. If localCacheScope=STATEMENT local session will be used just for statement execution, no data will be shared between two different calls to the same SqlSession.

SESSION | STATEMENT

SESSION

jdbcTypeForNull

Specifies the JDBC type for null values when no specific JDBC type was provided for the parameter. Some drivers require specifying the column JDBC type but others work with generic values like NULL, VARCHAR or OTHER.

JdbcType enumeration. Most common are: NULL, VARCHAR and OTHER

OTHER

lazyLoadTriggerMethods

Specifies which Object's methods trigger a lazy load

A method name list separated by commas

equals,clone,hashCode,toString

defaultScriptingLanguage

Specifies the language used by default for dynamic SQL generation.

A type alias or fully qualified class name.

org.apache.ibatis.scripting.xmltags.XMLDynamicLanguageDriver

callSettersOnNulls

当结果集中含有Null值时是否执行映射对象的setter或者Map对象的put方法。此设置对于原始类型如int,boolean等无效。

true | false

false

logPrefix

Specifies the prefix string that MyBatis will add to the logger names.

Any String

Not set

logImpl

Specifies which logging implementation MyBatis should use. If this setting is not present logging implementation will be autodiscovered.

SLF4J | LOG4J | LOG4J2 | JDK_LOGGING | COMMONS_LOGGING | STDOUT_LOGGING | NO_LOGGING

Not set

proxyFactory

Specifies the proxy tool that MyBatis will use for creating lazy loading capable objects.

CGLIB | JAVASSIST

CGLIB

一个设置信息元素的示例,完全的配置如下所示:

<settings>
    <setting name="cacheEnabled" value="true" />
    <setting name="lazyLoadingEnabled" value="true" />
    <setting name="multipleResultSetsEnabled" value="true" />
    <setting name="useColumnLabel" value="true" />
    <setting name="useGeneratedKeys" value="false" />
    <setting name="autoMappingBehavior" value="PARTIAL" />
    <setting name="defaultExecutorType" value="SIMPLE" />
    <setting name="defaultStatementTimeout" value="25" />
    <setting name="safeRowBoundsEnabled" value="false" />
    <setting name="mapUnderscoreToCamelCase" value="false" />
    <setting name="localCacheScope" value="SESSION" />
    <setting name="jdbcTypeForNull" value="OTHER" />
    <setting name="lazyLoadTriggerMethods" value="equals,clone,hashCode,toString" />
</settings>

1.1.3 typeAliases

 我们在sql映射xml文件中的引用实体类时,需要写上实体类的全类名(包名+类名),如下:

<insert id="addUser" parameterType="me.gacl.domain.User"> insert into users(name,age) values(#{name},#{age}) </insert>

parameterType="me.gacl.domain.User"这里写的实体类User的全类名me.gacl.domain.User,每次都写这么一长串内容挺麻烦的,而我们希望能够简写成下面的形式

<insert id="addUser" parameterType="me.gacl.domain.User"> insert into users(name,age) values(#{name},#{age}) </insert>

parameterType="_User"这样写就简单多了,为了达到这种效果,我们需要在conf.xml文件中为实体类="me.gacl.domain.User"定义一个别名为"_User",具体做法如下:

conf.xml文件中标签中添加如下配置:<typeAliases><typeAlias type="me.gacl.domain.User" alias="_User"/><typeAliases>

这样就可以为me.gacl.domain.User类定义了一个别名为_User,以后_User就代表了me.gacl.domain.User类,这样sql映射xml文件中的凡是需要引用me.gacl.domain.User类的地方都可以使用_User来代替,这就达到了一个简化实体类引用的目的。

 除了可以使用<typeAlias type="me.gacl.domain.User" alias="_User"/>这种方式单独为某一个实体类设置别名之外,我们还可以使用如下的方式批量为某个包下的所有实体类设置别名,如下:

<!-- 配置实体类的别名,配置实体类别名的目的是为了在引用实体类时可以使用实体类的别名来代替实体类,达到简写的目的 -->
    <typeAliases>
        <!-- 为实体类me.gacl.domain.User配置一个别名_User -->
        <!-- <typeAlias type="me.gacl.domain.User" alias="_User"/> -->
   为me.gacl.domain包下的所有实体类配置别名,MyBatis默认的设置别名的方式就是去除类所在的包后的简单的类名,
比如me.gacl.domain.User这个实体类的别名就会被设置成User
 
        <package name="me.gacl.domain"/>
    </typeAliases>

对model类进行别名的定义

别名

映射的类型

_byte

byte

_long

long

_short

short

_int

int

_integer

int

_double

double

_float

float

_boolean

boolean

string

String

byte

Byte

long

Long

short

Short

int

Integer

integer

Integer

double

Double

float

Float

boolean

Boolean

date

Date

decimal

BigDecimal

bigdecimal

BigDecimal

自定义别名

<!-- 自定义别名 -->
<typeAliases>
    <!--单个别名定义-->
    <!-- <typeAlias type="com.test.model.User" alias="User"/> -->
    <!-- 批量定义别名 (建议使用)-->
    <!-- package:指定包名称来为该包下的model类声明别名,默认的别名就是类型,首字符大小写均可-->
    <package name="cn.test.entity"/>
</typeAliases>
 
<!-- UserMapper.xml中使用别名 -->
<select id="findUserByUsername" parameterType="java.lang.String" resultType="User">
    SELECT * FROM tb_user WHERE username LIKE '%${value}%'
</select>

1.1.4 mappers

<mapper resource=’’/> 使用相对于类路径的资源,如:<mapper resource="sqlmap/User.xml" />

<mapper url=’’/> 使用完全限定路径,如:<mapper url="file:///D:\workspace_spingmvc\mybatis_01\config\sqlmap\User.xml"/>

<mapper class=’’/>  使用mapper接口的全限定名,如:<mapper class="com.com.test.mapper.UserMapper"/>
注意:此种方法要求mapper接口和mapper映射文件要名称相同,且放到同一个目录下;

<package name=’’/> 注册指定包下的所有映射文件,如:<package name="com.test.mapper"/>
注意:此种方法要求mapper接口和mapper映射文件要名称相同,且放到同一个目录下;

1.2 sql映射文件userMapper.xml

  • mapper接口的全限定名要和mapper映射文件的namespace值一致。
  • mapper接口的方法名称要和mapper映射文件的statement的id一致。
  • mapper接口的方法参数类型要和mapper映射文件的statement的parameterType的值一致,而且它的参数是一个。
  • mapper接口的方法返回值类型要和mapper映射文件的statement的resultType的值一致

user表的sql映射文件userMapper.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">
 <mapper namespace="me.gacl.mapping.userMapper">   
     <!-- 
         根据id查询得到一个user对象
      -->
     <select id="getUser" parameterType="int" 
         resultType="me.gacl.domain.User">
         select * from users where id=#{id}
     </select>
 </mapper>
  • namespace : 为这个mapper指定一个唯一的namespace,namespace的值习惯上设置成包名+sql映射文件名,这样就能够保证namespace的值是唯一的,例如namespace="me.gacl.mapping.userMapper"就是me.gacl.mapping(包名)+userMapper(userMapper.xml文件去除后缀)
  • 在select标签中编写查询的SQL语句, 设置select标签的id属性为getUser,id属性值必须是唯一的,不能够重复
    使用parameterType属性指明查询时使用的参数类型,resultType属性指明查询返回的结果集类型,resultType="me.gacl.domain.User"就表示将查询结果封装成一个User类的对象返回,User类就是users表所对应的实体类

select标签中属性:

  • id属性:标识映射文件中的sql,将sql语句封装到mapped statement对象中,所以称为statement的id
  • parameterType:指定输入参数类型
  • #{}:表示一个占位符
    #{userId}:其中的userId表示接收的输入参数,参数名称就是userId,如果输入参数是简单类型,#{}中的参数名可以任意,可以为value或者其他
  • ${}:表示拼接sql串,将接收到参数的内容不加任何修饰拼接在sql中,使用${}容易引起sql注入,${value}:接受输入参数的内容,如果传入类型是简单类型,${}中只能用value

  • resultType:指定sql输出结果的所映射的java对象类型,select指定resultType表示将单条记录映射成的java对象

在conf.xml文件中注册userMapper.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>
     <environments default="development">
         <environment id="development">
             <transactionManager type="JDBC" />
             <!-- 配置数据库连接信息 -->
             <dataSource type="POOLED">
                 <property name="driver" value="com.mysql.jdbc.Driver" />
                 <property name="url" value="jdbc:mysql://localhost:3306/mybatis" />
                 <property name="username" value="root" />
               <property name="password" value="XDP" />
             </dataSource>
         </environment>
     </environments>
     
     <mappers>
         <!-- 注册userMapper.xml文件, 
         userMapper.xml位于me.gacl.mapping这个包下,所以resource写成me/gacl/mapping/userMapper.xml-->
         <mapper resource="me/gacl/mapping/userMapper.xml"/>
     </mappers>
</configuration>

1.3 配置测试

public static void main(String[] args) throws IOException {
        //mybatis的配置文件
        String resource = "conf.xml";
        //使用类加载器加载mybatis的配置文件(它也加载关联的映射文件)
        InputStream is = Test1.class.getClassLoader().getResourceAsStream(resource);
        //构建sqlSession的工厂
        SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(is);
        //使用MyBatis提供的Resources类加载mybatis的配置文件(它也加载关联的映射文件)
        //Reader reader = Resources.getResourceAsReader(resource); 
        //构建sqlSession的工厂
        //SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(reader);
        //创建能执行映射文件中sql的sqlSession
        SqlSession session = sessionFactory.openSession();
        /**
         * 映射sql的标识字符串,
         * me.gacl.mapping.userMapper是userMapper.xml文件中mapper标签的namespace属性的值,
         * getUser是select标签的id属性值,通过select标签的id属性值就可以找到要执行的SQL
         */
        String statement = "me.gacl.mapping.userMapper.getUser";//映射sql的标识字符串
        //执行查询返回一个唯一user对象的sql
        User user = session.selectOne(statement, 1);
        System.out.println(user);
    }

2 使用MyBatis对表执行CRUD操作——基于注解的实现

2.1 mapper接口

import java.util.List;
import me.gacl.domain.User;
import org.apache.ibatis.annotations.Delete;
 import org.apache.ibatis.annotations.Insert;
 import org.apache.ibatis.annotations.Select;
 import org.apache.ibatis.annotations.Update;
 
 /**
  * @author gacl
  * 定义sql映射的接口,使用注解指明方法要执行的SQL
  */
 public interface UserMapperI {
 
     使用@Insert注解指明add方法要执行的SQL
     @Insert("insert into users(name, age) values(#{name}, #{age})")
     public int add(User user);
     
     使用@Delete注解指明deleteById方法要执行的SQL
     @Delete("delete from users where id=#{id}")
     public int deleteById(int id);
     
     使用@Update注解指明update方法要执行的SQL
     @Update("update users set name=#{name},age=#{age} where id=#{id}")
     public int update(User user);
     
     使用@Select注解指明getById方法要执行的SQL
     @Select("select * from users where id=#{id}")
     public User getById(int id);
     
     使用@Select注解指明getAll方法要执行的SQL
     @Select("select * from users")
     public List<User> getAll();
 }

需要说明的是,不需要针对UserMapperI接口去编写具体的实现类代码,这个具体的实现类由MyBatis帮我们动态构建出来,我们只需要直接拿来使用即可

2.2 配置conf.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>
     <environments default="development">
         <environment id="development">
             <transactionManager type="JDBC" />
             <!-- 配置数据库连接信息 -->
             <dataSource type="POOLED">
                 <property name="driver" value="com.mysql.jdbc.Driver" />
                 <property name="url" value="jdbc:mysql://localhost:3306/mybatis" />
                 <property name="username" value="root" />
                 <property name="password" value="XDP" />
             </dataSource>
         </environment>
     </environments>
     
     <mappers>
         <!-- 注册userMapper.xml文件, 
         userMapper.xml位于me.gacl.mapping这个包下,所以resource写成me/gacl/mapping/userMapper.xml-->
         <mapper resource="me/gacl/mapping/userMapper.xml"/>
         <!-- 注册UserMapper映射接口-->
         <mapper class="me.gacl.mapping.UserMapperI"/>
     </mappers>
     
 </configuration>

2.3 测试类

 public class TestCRUDByAnnotationMapper {
 
     @Test
     public void testAdd(){
         SqlSession sqlSession = MyBatisUtil.getSqlSession(true);
         //得到UserMapperI接口的实现类对象,UserMapperI接口的实现类对象由sqlSession.getMapper(UserMapperI.class)动态构建出来
         UserMapperI mapper = sqlSession.getMapper(UserMapperI.class);
         User user = new User();
         user.setName("用户xdp");
         user.setAge(20);
         int add = mapper.add(user);
         //使用SqlSession执行完SQL之后需要关闭SqlSession
         sqlSession.close();
         System.out.println(add);
     }

}

用到的工具类

public class MyBatisUtil {
 
     /**
      * 获取SqlSessionFactory
      * @return SqlSessionFactory
      */
     public static SqlSessionFactory getSqlSessionFactory() {
         String resource = "conf.xml";
         InputStream is = MyBatisUtil.class.getClassLoader().getResourceAsStream(resource);
         SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
         return factory;
     }
     
     /**
      * 获取SqlSession
      * @return SqlSession
      */
     public static SqlSession getSqlSession() {
         return getSqlSessionFactory().openSession();
     }
     
     /**
      * 获取SqlSession
      * @param isAutoCommit 
      *         true 表示创建的SqlSession对象在执行完SQL之后会自动提交事务
      *         false 表示创建的SqlSession对象在执行完SQL之后不会自动提交事务,这时就需要我们手动调用sqlSession.commit()提交事务
      * @return SqlSession
      */
     public static SqlSession getSqlSession(boolean isAutoCommit) {
         return getSqlSessionFactory().openSession(isAutoCommit);
     }
}

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值