记录KIte的学习历程

Kite学习框架的第六天

昨天晚上还学习了mybatis的一级二级缓存,分别是在session中的缓存,和在SqlSessionFactory中的缓存
在session中有一个清理缓存的方法:session.clearCache();
这里就不详细介绍了

1.使用注解实现CRUD操作

1.1 实现数据的查找,并且在实体类中的属性名,与数据库中的属性名不同的情况下(我这里只是把实体类中的id改为了userId)

1.1.1 创建实体类User

package cn.kitey.domain;

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

/**
 * 用户类实体类实现序列化接口
 */
public class User implements Serializable {

    private Integer userId;
    private String username;
    private String sex;
    private String address;
    private Date birthday;

    public User() {
    }

    public User(Integer userId, String username, String sex, String address, Date birthday) {
        this.userId = userId;
        this.username = username;
        this.sex = sex;
        this.address = address;
        this.birthday = birthday;
    }

    public String getUsername() {
        return username;
    }

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

    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;
    }

    public Date getBirthday() {
        return birthday;
    }

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

    public Integer getUserId() {
        return userId;
    }

    public void setUserId(Integer userId) {
        this.userId = userId;
    }

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

1.1.2 创建永久层接口UserDao


package cn.kitey.dao;

import cn.kitey.domain.User;
import org.apache.ibatis.annotations.*;

import java.util.List;

public interface UserDao {

    /**
     * 使用注解实现数据的查找
     * @return
     */
    @Select("select * from user")
    //配置结果集(可以用于实体类中的名称于数据库名称不对应的场景)
    //id 为再次使用结果集时不需要重新配置results
    @Results(id = "resultMap", value = {
            @Result(id = true, column = "id", property ="userId" ),
            @Result(column ="username" ,property ="username" ),
            @Result(column ="sex" ,property ="sex" ),
            @Result(column ="address" ,property ="address" ),
            @Result(column ="birthday" ,property ="birthday" )
    })
    public List<User> findAll();


}

其中的@results注解用来封装结果集:
id :结果集的名称
value:包含各条数据
@Result:分装一个个属性值
id = true 表示该属性为主键
property:表示实体类中的属性名
colum:表示数据库中的属性名称(数据库中可以不区分大小写)

1.1.3 创建测试类

package cn.kitey.test;

import cn.kitey.dao.UserDao;
import cn.kitey.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 MyBatisAnnotationTest {
    private InputStream inputStream;
    SqlSession session;
    UserDao userDao;
    @Before
    public void init()  {
        try {
            //读取文件输入流
            inputStream   = Resources.getResourceAsStream("SqlMapConfig.xml");
            //获取SqlSessionFactory
            SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
            SqlSessionFactory factory = builder.build(inputStream);
            //获取session对象
            session = factory.openSession();
            //获取代理对象
            userDao = session.getMapper(UserDao.class);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    @After
    public void destroy(){
        //进行事务的提交
        session.commit();

        //释放资源
        session.close();
        try {
            if( inputStream != null){
                inputStream.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }



    @Test
    public void FindAllTest(){
        List<User> all = userDao.findAll();
        for (User user : all) {
            System.out.println(user);
        }

    }


}

测试结果图:

记录KIte的学习历程_第1张图片

1.2 数据的插入

1.2.1 在dao中加入插入数据的方法,并给上注解

    /**
     * 使用注解实现书数据的插入
     * @param user
     */
    @Insert("insert into user(username, sex, address, birthday)" +
            " values(#{username}, #{sex}, #{address}, #{birthday})")
    public void insertUser(User user);

1.2.1 在测试类中进行测试,添加测试方法

 @Test
    public void insertUserTest(){
        User userDate = new User();
        userDate.setUsername("赵云");
        userDate.setSex("男");
        userDate.setAddress("three KingDom");
        userDate.setBirthday(new Date());
        userDao.insertUser(userDate);

        List<User> all = userDao.findAll();
        for (User user : all) {
            System.out.println(user);
        }
    }

结果图:这里我重新插入了赵云insert2 ,并进行了数据的查询
记录KIte的学习历程_第2张图片

1.3 按照id查询,这里我是为了验证前面定义resultMap是否可以使用别名在findById方法注解中使用

1.3.1 在UserDao中创建方法,并加以注解

这里注意结果集用的时 @ResultMap(value = {“resultMap”})
resultMap:为上面定义的
@Results(id = “resultMap”, value = {
@Result(id = true, column = “id”, property =“userId” ),
@Result(column =“username” ,property =“username” ),
@Result(column =“sex” ,property =“sex” ),
@Result(column =“address” ,property =“address” ),
@Result(column =“birthday” ,property =“birthday” )
})

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

1.3.2 测试类进行测试

    @Test
    public void findByIdTest(){
        User byId = userDao.findById(1);
        System.out.println(byId);
    }


运行结果图:
在这里插入图片描述

还用删除,数据跟新等操作就不进行演示了,原理一样只要修改注解的sql语句就可以了
注意:
更新使用注解@update
删除使用注解:@delete

2.使用注解实现一对一的查询

(即:在account表中进行查询的时候,查到一个account信息的同时输出对应的user信息 )

2.1 创建Account实体类,其中包括user的信息

package cn.kitey.domain;

import java.io.Serializable;

public class Account implements Serializable {
    private Integer id;
    private Integer uid;
    private Double money;
    //多队一的映射,
    private User user;

    public User getUser() {
        return user;
    }

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

    public Integer getId() {
        return id;
    }

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

    public Integer getUid() {
        return uid;
    }

    public void setUid(Integer uid) {
        this.uid = uid;
    }

    public Double getMoney() {
        return money;
    }

    public void setMoney(Double money) {
        this.money = money;
    }

    @Override
    public String toString() {
        return "Account{" +
                "id=" + id +
                ", uid=" + uid +
                ", money=" + money +
                '}';
    }
}


2.2 创建AccountDao接口添加查询方法

package cn.kitey.dao;

import cn.kitey.domain.Account;
import org.apache.ibatis.annotations.One;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.mapping.FetchType;

import java.util.List;

public interface AccountDao {

    @Select("select *from account")
    @Results(id = "AccountMap" ,value = {
            @Result(id = true, property = "id" , column = "id"),
            @Result(property = "uid", column = "uid"),
            @Result(property = "money", column = "money"),
            @Result(property = "user", column = "uid" ,
                    //fetchType = FetchType.EAGER):表示立即加载
                    one=@One(select = "cn.kitey.dao.UserDao.findById", fetchType = FetchType.EAGER))
    })
    List<Account> findALl();
}

注解的解释:
@Result(property = “user”, column = “uid” ,
//fetchType = FetchType.EAGER):表示立即加载
one=@One(select = “cn.kitey.dao.UserDao.findById”, fetchType = FetchType.EAGER))
其中one表示为一对一查询结果,这时要在selec中填写userdao的全限定类名加上方法,fetchType = FetchType.EAGER):表示立即加载

重点:
一对一查询通常使用立即加载
一对多查询通常使用延迟加载

2.3 添加测试类AccountTest

package cn.kitey.test;

import cn.kitey.dao.AccountDao;
import cn.kitey.dao.UserDao;
import cn.kitey.domain.Account;
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 AccountTest {

    private InputStream inputStream;
    SqlSession session;
    AccountDao accountDao;
    @Before
    public void init()  {
        try {
            //读取文件输入流
            inputStream   = Resources.getResourceAsStream("SqlMapConfig.xml");
            //获取SqlSessionFactory
            SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
            SqlSessionFactory factory = builder.build(inputStream);
            //获取session对象
            session = factory.openSession();
            //获取代理对象
            accountDao = session.getMapper(AccountDao.class);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    @After
    public void destroy(){
        //进行事务的提交
        session.commit();

        //释放资源
        session.close();
        try {
            if( inputStream != null){
                inputStream.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Test
    public void findAll(){
        List<Account> aLl1 = accountDao.findALl();
        for (Account account : aLl1){
            System.out.println("------每一个账户信息---------");
            System.out.println(account);
            System.out.println(account.getUser());
        }
    }
}

运行结果图:
记录KIte的学习历程_第3张图片
这时账户信息中就包含了user信息

加油,下午的学习内容!

你可能感兴趣的:(每天的学习笔记)