侧边栏壁纸
博主头像
coydone博主等级

记录学习,分享生活的个人站点

  • 累计撰写 306 篇文章
  • 累计创建 51 个标签
  • 累计收到 0 条评论

目 录CONTENT

文章目录

Mybatis注解开发

coydone
2022-03-11 / 0 评论 / 0 点赞 / 368 阅读 / 10,780 字 / 正在检测是否收录...
温馨提示:
本文最后更新于 2022-04-10,若内容或图片失效,请留言反馈。部分素材来自网络,若不小心影响到您的利益,请联系我们删除。

Mybatis的常用注解

@Insert:实现新增
@Update:实现更新
@Delete:实现删除
@Select:实现查询
@Result:实现结果集封装
@Results:可以与@Result 一起使用,封装多个结果集
@ResultMap:实现引用@Results 定义的封装
@One:实现一对一结果集封装
@Many:实现一对多结果集封装
@SelectProvider: 实现动态 SQL 映射
@CacheNamespace:实现注解二级缓存的使用

单表增删改查

1、环境准备

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.coydone</groupId>
    <artifactId>mybatis01_annotation</artifactId>
    <version>1.0-SNAPSHOT</version>

    <packaging>jar</packaging>

    <dependencies>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.5</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.6</version>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.12</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.10</version>
        </dependency>
    </dependencies>
</project>

resources下配置文件

数据库连接配置:jdbc.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/eesy_mybatis
jdbc.username=root
jdbc.password=root123

日志输出配置:log4j.properties

# Set root category priority to INFO and its only appender to CONSOLE.
#log4j.rootCategory=INFO, CONSOLE            debug   info   warn error fatal
log4j.rootCategory=debug, CONSOLE, LOGFILE

# Set the enterprise logger category to FATAL and its only appender to CONSOLE.
log4j.logger.org.apache.axis.enterprise=FATAL, CONSOLE

# CONSOLE is set to be a ConsoleAppender using a PatternLayout.
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n

# LOGFILE is set to be a File appender using a PatternLayout.
log4j.appender.LOGFILE=org.apache.log4j.FileAppender
log4j.appender.LOGFILE.File=d:\axis.log
log4j.appender.LOGFILE.Append=true
log4j.appender.LOGFILE.layout=org.apache.log4j.PatternLayout
log4j.appender.LOGFILE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n

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">
<configuration>
    <!-- 引入外部配置文件-->
    <properties resource="jdbc.properties"></properties>
    <!--配置别名-->
    <typeAliases>
        <package name="com.coydone.entity"></package>
    </typeAliases>
    <!-- 配置环境-->
    <environments default="mysql">
        <environment id="mysql">
            <transactionManager type="JDBC"></transactionManager>
            <dataSource type="POOLED">
                <property name="driver" value="${jdbc.driver}"></property>
                <property name="url" value="${jdbc.url}"></property>
                <property name="username" value="${jdbc.username}"></property>
                <property name="password" value="${jdbc.password}"></property>
            </dataSource>
        </environment>
    </environments>
    <!-- 指定带有注解的dao接口所在位置 -->
    <mappers>
        <package name="com.coydone.mapper"></package>
        <!--<mapper class="com.coydone.mapper.UserMapper"></mapper>-->
    </mappers>
</configuration>

2、编写实体类

实体类User

public class User implements Serializable {
    private Integer id;
    private String username;
    private Date birthday;
    private String sex;
    private String address;
}

3、编写持久层接口Mapper。

持久层接口UserMapper.java

public interface UserMapper {
    //查询所有用户
    @Select("select * from user")
    List<User> findAll();
    
    @Insert("insert into user(username,address,sex,birthday)values(#{username},#{address},#{sex},#{birthday})")
    void saveUser(User user);
    
    @Update("update user set username=#{username},sex=#{sex},birthday=#{birthday},address=#{address} where id=#{id}")
    void updateUser(User user);
    
    @Delete("delete from user where id=#{id}")
    void deleteUser(Integer id);
    
    @Select("select * from user where id=#{id}")
    User findById(Integer id);

    // 根据用户名称模糊查询
    @Select("select * from user where username like #{username}")
    //@Select("select * from user where username like '%${value}%'")
    List<User> findUserByName(String username);

    @Select("select count(*) from user")
    Integer findTotalUser();
}

4、编写测试类

public class AnnotationCRUDTest {
    private InputStream in;
    private SqlSessionFactory factory;
    private SqlSession session;
    private UserMapper userMapper;

    @Before
    public void init() throws Exception{
        in = Resources.getResourceAsStream("mybatis-config.xml");
        factory = new SqlSessionFactoryBuilder().build(in);
        session = factory.openSession();
        userDao = session.getMapper(UserMapper.class);
    }
    @After
    public void destroy() throws Exception{
        session.commit();
        session.close();
        in.close();
    }

    @Test
    public void testSave(){
        User user = new User();
        user.setUsername("tom");
        user.setAddress("北京市昌平区");

        userMapper.saveUser(user);
    }

    @Test
    public void testUpdate(){
        User user = new User();
        user.setId(51);
        user.setUsername("tom");
        user.setAddress("北京市昌平区");
        user.setSex("男");
        user.setBirthday(new Date());

        userMapper.updateUser(user);
    }

    @Test
    public void testDelete(){
        userMapper.deleteUser(50);
    }

    @Test
    public void testFindById(){
        User user = userMapper.findById(51);
        System.out.println(user);
    }

    @Test
    public void testFindByName(){
        List<User> users = userMapper.findUserByName("%王%");
        //List<User> users = userMapper.findUserByName("王");
        for (User user : users) {
            System.out.println(user);
        }
    }

    @Test
    public void testFindTotal(){
        Integer totalUser = userMapper.findTotalUser();
        System.out.println(totalUser);
    }
}

数据库字段名与实体类属性不对应时实体类

public class User implements Serializable {
    private Integer userId;
    private String userName;
    private Date userBirthday;
    private String userSex;
    private String userAddress;
}

IUserDao

public interface IUserDao {
    /**
     * 查询所有用户
     * @return
     */
    @Select("select * from user")
    @Results(id = "userMap",value = {
            @Result(id = true,column = "id",property = "userId"),
            @Result(column = "username",property = "userName"),
            @Result(column = "address",property = "userAddress"),
            @Result(column = "sex",property = "userSex"),
            @Result(column = "birthday",property = "userBirthday")
    })
    List<User> findAll();

    @Select("select * from user where id=#{id}")
    @ResultMap("userMap")
    User findById(Integer id);
}

多表查询

实现复杂关系映射之前我们可以在映射文件中通过配置来实现,在使用注解开发时我们需要借助@Results 注解,@Result 注解,@One 注解,@Many 注解。

复杂关系映射的注解说明

@Results 注解

代替的是标签<resultMap>

该注解中可以使用单个@Result 注解,也可以使用@Result 集合

@Results({@Result(),@Result()})@Results(@Result())

@Result注解

代替了 <id>标签和<result>标签

属性介绍:

  • id 是否是主键字段

  • column 数据库的列名

  • property 需要装配的属性名

  • one 需要使用的@One 注解(@Result(one=@One)())

  • many 需要使用的@Many 注解(@Result(many=@many)())

@One 注解(一对一)

代替了标签,是多表查询的关键,在注解中用来指定子查询返回单一对象。

@属性介绍:

  • select 指定用来多表查询的 sqlmapper

  • fetchType 会覆盖全局的配置参数 lazyLoadingEnabled使用格式:@Result(column=" ",property="",one=@One(select=""))

@Many 注解(多对一)

代替了<Collection>标签,是多表查询的关键,在注解中用来指定子查询返回对象集合。

注意:聚集元素用来处理“一对多”的关系。需要指定映射的 Java 实体类的属性,属性的 javaType(一般为 ArrayList)但是注解中可以不定义。

使用格式:@Result(property="",column="",many=@Many(select=""))

一对一及延迟加载

需求:加载账户信息时并且加载该账户的用户信息,根据情况可实现延迟加载。(注解方式实现)

创建Account的账户实体类

public class Account implements Serializable {
    private Integer id;
    private Integer uid;
    private Double money;

    //多对一(mybatis中称之为一对一)的映射,一个账户只能属于一个用户。
    private User user;
}

持久层Mapper接口

public interface AccountMapper {
    // 查询所有账户,并且获取每个账户所属的用户信息
    @Select("select * from account")
    @Results(id = "accountMap",value = {
            @Result(id = true,column = "id",property = "id"),
            @Result(column = "uid",property = "uid"),
            @Result(column = "money",property = "money"),
            @Result(column = "uid",property = "user",one = @One(select="com.coydone.mapper.UserMapper.findById",fetchType= FetchType.EAGER))
    })
    List<Account> findAll();
}

测试类

public class AccountTest {
    private InputStream in;
    private SqlSessionFactory factory;
    private SqlSession session;
    private AccountMapper accountMapper;

    @Before
    public void init() throws Exception{
        in = Resources.getResourceAsStream("mybatis-config.xml");
        factory = new SqlSessionFactoryBuilder().build(in);
        session = factory.openSession();
        accountMapper = session.getMapper(AccountMapper.class);
    }
    @After
    public void destroy() throws Exception{
        session.commit();
        session.close();
        in.close();
    }

    @Test
    public void testFindAll(){
        List<Account> accounts = accountMapper.findAll();
        for (Account account : accounts) {
            System.out.println(account);
            System.out.println(account.getUser());
        }
    }
}

一对多

查询所有用户并显示其对应的账户信息

public class User implements Serializable {
    private Integer userId;
    private String userName;
    private Date userBirthday;
    private String userSex;
    private String userAddress;

    //一对多关系映射:一个用户对于多个账户
    private List<Account> accounts;
}

AccountMapper

//根据用户id查询账户信息
@Select("select * from account where uid=#{userId}")
List<Account> findAccountByUid(Integer userId);

UserMapper

public interface UserMapper {
    //查询所有用户
    @Select("select * from user")
    @Results(id = "userMap",value = {
            @Result(id = true,column = "id",property = "userId"),
            @Result(column = "username",property = "userName"),
            @Result(column = "address",property = "userAddress"),
            @Result(column = "sex",property = "userSex"),
            @Result(column = "birthday",property = "userBirthday"),
            @Result(column = "id",property = "accounts",
                    many = @Many(select="com.coydone.mapper.AccountMapper.findAccountByUid",
                            fetchType = FetchType.LAZY))
    })
    List<User> findAll();
}

其中column = "id"是绑定User中的主键,property = "accounts"是User类中映射关系的属性名,select="com.coydone.mapper.AccountMapper.findAccountByUid"是通过用户id查询account表的全限定类名+方法名。

测试类

@Test
public void testFindAll(){
    List<User> users = userMapper.findAll();
    for (User user : users) {
        System.out.println(user);
        System.out.println(user.getAccounts());
    }
}

开启二级缓存

@CacheNamespace(blocking = true)
public interface UserMapper {}

同时让Mybatis支持二级缓存,在mybatis-config.xml中开启。

<!--配置开启二级缓存-->
<settings>
    <setting name="cacheEnabled" value="true"/>
</settings>
0

评论区