Mybatis学习笔记-注解配置开发

一世执手 提交于 2020-02-05 01:42:21

总览

1.准备工作

 (1) 创建一个database以及user表,account表,role表,role_user表(使用mysql) 返回文章开头

#创建mybatis数据库
CREATE DATABASE mybatis;
#使用数据库
USE mybatis
#存在则删除user表
DROP TABLE IF EXISTS `user`;
#创建user表
CREATE TABLE `user` (
  `id` int(11) NOT NULL auto_increment,
  `username` varchar(32) NOT NULL COMMENT '用户名称',
  `birthday` datetime default NULL COMMENT '生日',
  `sex` char(1) default NULL COMMENT '性别',
  `address` varchar(256) default NULL COMMENT '地址',
  PRIMARY KEY  (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
#插入一些测试数据
insert  into `user`(`id`,`username`,`birthday`,`sex`,`address`) 
values (41,'老王','2018-02-27 17:47:08','男','北京'),
(42,'小二王','2018-03-02 15:09:37','女','北京金燕龙'),
(43,'小二王','2018-03-04 11:34:34','女','北京金燕龙')
#存在则删除account表
DROP TABLE IF EXISTS `account`;
#创建account表
CREATE TABLE `account` (
  `ID` int(11) NOT NULL COMMENT '编号',
  `UID` int(11) default NULL COMMENT '用户编号',
  `MONEY` double default NULL COMMENT '金额',
  PRIMARY KEY  (`ID`),
  KEY `FK_Reference_8` (`UID`),
  CONSTRAINT `FK_Reference_8` FOREIGN KEY (`UID`) REFERENCES `user` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
#插入一些测试数据
insert  into `account`(`ID`,`UID`,`MONEY`) values (1,46,1000),(2,45,1000),(3,46,2000);

 (2) 实体类User 返回文章开头

package cn.itcast.domain;


import java.io.Serializable;
import java.util.Date;
import java.util.List;

public class User implements Serializable {

    private Integer id;//用户唯一标识
    private String username;//用户名
    private Date birthday;//生日
    private String sex;//性别
    private String address;//地址
    //一对多映射,主表实体应该包含从表实体的集合引用
    private List<Account> accounts;
    
    public List<Account> getAccounts() { return accounts; }

    public void setAccounts(List<Account> accounts) { this.accounts = accounts; }


    public Integer getId() { return id; }

    public void setId(Integer id) { this.id = id; }

    public String getUsername() { return username; }

    public void setUsername(String username) { this.username = username; }

    public Date getBirthday() { return birthday; }

    public void setBirthday(Date birthday) { this.birthday = birthday; }

    public String getSex() { return sex; }

    public void setSex(String sex) { this.sex = sex; }

    public String getAddress() { return address; }

    public void setAddress(String address) { this.address = address; }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", birthday=" + birthday +
                ", sex='" + sex + '\'' +
                ", address='" + address + '\'' +
                ", accounts=" + accounts +
                ", roles=" + roles +
                '}';
    }
}

 (3) 实体类Account 返回文章开头

package cn.itcast.domain;

public class Account {
    private Integer account_id;
    private Integer account_uid;
    private Double account_money;
    //一个账户对应一个用户(一对一),此处定义一个User对象引用
    private User user;

    public User getUser() { return user; }

    public void setUser(User user) { this.user = user; }

    public Integer getAccount_id() { return account_id; }

    public void setAccount_id(Integer account_id) { this.account_id = account_id; }

    public Integer getAccount_uid() { return account_uid; }

    public void setAccount_uid(Integer account_uid) { this.account_uid = account_uid; }

    public Double getAccount_money() { return account_money; }

    public void setAccount_money(Double account_money) { this.account_money = account_money; }

    @Override
    public String toString() {
        return "Account{" +
                "account_id=" + account_id +
                ", account_uid=" + account_uid +
                ", account_money=" + account_money +
                ", user=" + user +
                '}';
    }
}

 (4) dao.UserDao 返回文章开头

package cn.itcast.dao;

import cn.itcast.domain.User;
import org.apache.ibatis.annotations.*;
import org.apache.ibatis.mapping.FetchType;

import java.util.List;

/**
 * 在Mybatis中,针对CRUD有4个注解
 * @Select,@Insert,@Update,@Delete
 */
//开启二级缓存
@CacheNamespace(blocking = true)
public interface UserDao {

    /**
     * 查询所有用户
     * @returnList<User>
     */
    @Select("select * from user")
    //配置实体类的属性与数据库字段的对应关系
    //Results注解的id唯一标识这个映射表,这样可以供其他方法使用(方法指定ResultMap注解)
    @Results(id = "defaultMap",value = {
    		//id默认为false,当指定为true时说明此实体属性是主键
    		//property为实体类属性名,column为对应的数据库字段名
            @Result(id = true,property = "id",column = "id"),
            @Result(property = "username",column = "username"),
            @Result(property = "sex",column = "sex"),
            @Result(property = "address",column = "address"),
            @Result(property = "birthday",column = "birthday"),
            //多表查询(一对多关系)
            @Result(property = "accounts",column = "id",
            //many属性其类型是一个Many注解,可以指定关联查询的sql语句的位置和是否开启延迟加载,它代表此实体类属性是一个关联对象的集合(即查询与之有一对多关系的数据库表才能得到的对象集合)
                    many = @Many(select = 
//select属性用于指定关联查询的sql语句的位置,mybatis会根据cn.itcast.dao.AccountDao.findByUid这个方法定义的sql语句,传入column属性的值作为查询条件参数的实参执行sql语句,fetchType属性用于开启延迟加载或者立即加载,FetchType.LAZY代表延迟加载
"cn.itcast.dao.AccountDao.findByUid",fetchType = FetchType.LAZY))

    })
    List<User> findAll();

    /**
     * 根据id查询一个用户
     * @param id
     * @return User
     */
    @Select("select * from user where id = #{id}")
    @ResultMap("defaultMap")
    User findOne(Integer id);

    /**
     * 保存用户
     * @param user
     */
    @Insert("insert into user(username,sex,address,birthday)values(#{username},#{sex},#{address},#{birthday})")
    void saveUser(User user);

    /**
     * 更新用户
     * @param user
     */
    @Update("update user set username=#{username},sex=#{sex},address=#{address},birthday=#{birthday} where id = #{id}")
    void updateUser(User user);


    /**
     * 根据id删除用户
     * @param id
     */
    @Delete("delete from user where id = #{id}")
    void deleteUser(Integer id);

    /**
     * 查询总记录数
     * @return
     */
    @Select("select count(*) from user")
    int findTotal();

}

 (5) dao.AccountDao 返回文章开头

package cn.itcast.dao;

import cn.itcast.domain.Account;
import org.apache.ibatis.annotations.*;
import org.apache.ibatis.mapping.FetchType;

import java.util.List;

public interface AccountDao {


    /**
     * 查询所有账户
     * @return List<Account>
     */
    @Select("select * from account")
    @Results(id = "defaultMap",value = {
            @Result(id = true,property = "account_id",column = "id"),
            @Result(property = "account_uid",column = "uid"),
            @Result(property = "account_money",column = "money"),
            @Result(property = "user",column = "uid",
            //One属性其类型是一个One注解,可以指定关联查询的sql语句的位置和是否开启延迟加载。它代表此实体类属性是一个关联对象(即需要查询与之有一对一关系的数据库表后才能得到的对象)
                    one = @One(select = 
//select属性用于指定关联查询的sql语句的位置,mybatis会根据cn.itcast.dao.AccountDao.findByUid这个方法定义的sql语句,传入column属性的值作为查询条件参数的实参执行sql语句,fetchType属性用于开启延迟加载或者立即加载,FetchType.EAGER代表延迟加载
"cn.itcast.dao.UserDao.findOne",fetchType = FetchType.EAGER))
                   
    })
    List<Account> findAll();

    /**
     * 根据id查找一个账户
     * @param uid
     * @return Account
     */
    @Select("select * from account where uid = #{uid}")
    @ResultMap("defaultMap")
    List<Account> findByUid(Integer uid);
}

2.xml配置文件

 (1) mybatis-config.xml(放在resources目录下) 返回文章开头

<?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>
    <!--引入存储数据库连接的4个基本信息的配置文件-->
    <properties resource="jdbcConfig.properties"/>
    <!--全局开启二级缓存-->
    <settings>
        <setting name="cacheEnabled" value="true"/>
    </settings>
    <!--为所有实体类注册别名,别名为不区分大小写的类名-->
    <typeAliases><package name="cn.itcast.domain"/></typeAliases>
    <environments default="dev_mysql">
        <!--开发环境下的mysql配置-->
        <environment id="dev_mysql">
            <!--配置事务类型-->
            <transactionManager type="JDBC"></transactionManager>
            <!--配置数据源类型-->
            <dataSource type="POOLED">
                <!--引用jdbcConfig.properties中存储的数据库连接的基本信息-->
                <property name="driver" value="${jdbc.driver}"/>
                <property name="url" value="${jdbc.url}"/>
                <property name="username" value="${jdbc.username}"/>
                <property name="password" value="${jdbc.password}"/>
            </dataSource>
        </environment>
    </environments>

    <!--配置映射文件-->
    <mappers>
        <!--指出带有注解的dao接口所在位置-->
        <package name="cn.itcast.dao"/>
    </mappers>
</configuration>

3.运行测试

 (1) UserDaoTest 返回文章开头

package cn.itcast;

import cn.itcast.dao.UserDao;
import cn.itcast.domain.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.List;

public class UserDaoTest {
    private InputStream in;
    private SqlSession session;
    private UserDao userDao;

    @Before
    public void init() throws IOException {
        //1.获取mybatis配置文件的字节输入流
        in = Resources.getResourceAsStream("mybatis-config.xml");
        //2.使用构建者构建SqlSessionFactory对象
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
        //3.使用SqlSessionFactory对象生产SqlSession
        session = factory.openSession();
        //4.使用session创建dao代理对象
        userDao = session.getMapper(UserDao.class);
    }

    @After
    public void destroy() throws IOException {
        //提交事务
        session.commit();
        //释放资源
        session.close();
        in.close();
    }

    /**
     * 测试 查询所有用户
     */
    @Test
    public void findAllTest() {
        List<User> users = userDao.findAll();
        for (User user : users) {
            System.out.println(user);
        }
    }
    /**
     * 测试 查询一个用户
     */
    @Test
    public void findOneTest() {
        User user = userDao.findOne(46);
        System.out.println(user);
    }

    /**
     * 测试 保存用户
     */
    @Test
    public void saveUserTest() {
        User user = new User();
        user.setUsername("mybatis_save_user");
        user.setBirthday(new Date());
        user.setAddress("江苏");
        user.setSex("男");

        userDao.saveUser(user);
    }
    /**
     * 测试 更新用户
     */
    @Test
    public void updateUserTest() {
        User user = new User();
        user.setUsername("mybatis_update_user");
        user.setBirthday(new Date());
        user.setAddress("江苏_update");
        user.setSex("女");
        user.setId(67);

        userDao.updateUser(user);
    }

    /**
     * 测试 删除用户
     */
    @Test
    public void deleteUserTest() {
        userDao.deleteUser(60);
    }

    /**
     * 测试 查询user表总记录数
     */
    @Test
    public void findTotalTest() {
        int total = userDao.findTotal();
        System.out.println("user表总记录数:共" + total + "条");
    }
}

 (2) AccountDaoTest 返回文章开头

package cn.itcast;

import cn.itcast.dao.AccountDao;
import cn.itcast.dao.UserDao;
import cn.itcast.domain.Account;
import cn.itcast.domain.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class AccountDaoTest {
    private InputStream in;
    private SqlSession session;
    private AccountDao accountDao;

    @Before
    public void init() throws IOException {
        //1.获取mybatis配置文件的字节输入流
        in = Resources.getResourceAsStream("mybatis-config.xml");
        //2.使用构建者构建SqlSessionFactory对象
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
        //3.使用SqlSessionFactory对象生产SqlSession
        session = factory.openSession();
        //4.使用session创建dao代理对象
        accountDao = session.getMapper(AccountDao.class);
    }

    @After
    public void destroy() throws IOException {
        //释放资源
        session.close();
        in.close();
    }

    /**
     * 测试 查询 所有账户
     */
    @Test
    public void findAllTest() {
        List<Account> accounts = accountDao.findAll();
        for (Account account : accounts) {
            System.out.println(account);
        }
    }

    /**
     *  测试 根据uid查询一个账户
     */
    @Test
    public void findOneTest() {
        List<Account> accounts = accountDao.findByUid(46);
        for (Account account : accounts) {
            System.out.println(account);
        }
    }
}

注:
项目目录结构返回文章开头
在这里插入图片描述
log4j.properties返回文章开头
  在项目中编写Sysem.out.prinltn()的时候,是输出到控制台的,当项目发布到tomcat之后,是没有控制台的,不过可以在命令行界面还能看见,但是不容易观察一些输出结果。log4j是由apache推出的一个开源免费的日志处理的类库,不仅仅可以把内容输出到控制台,还能把内容输出到文件中。便于观察结果。

# 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

jdbcConfig.properties返回文章开头

jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis?CharacterEncoding=utf-8&serverTimezone=UTC
jdbc.username=root
jdbc.password=root

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>cn.itcast</groupId>
    <artifactId>Mybatis_day02</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>

    <dependencies>
        <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.6</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.15</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/log4j/log4j -->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/junit/junit -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
</project>

参考: Mybatis笔记(一)-----Mybatis基础xml配置文件解释

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!