Mybatis 一对一 使用

第一步:

映射了需要构建User 类型

 

 Domain =》Account 代码

package com.itheima.domain;

import java.io.Serializable;

public class Account implements Serializable {
    private Integer id;
    private Integer uid;
    private Double money;
    //多对一 (mybatis 称之为一对一)的映射,一个账户只能属于一个用户
    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 +
                '}';
    }
}

Domain =》User代码

package com.itheima.domain;

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

public class User implements Serializable {

   private  Integer userid;
   private  String username;
   private String  useraddress;
   private String usersex;
   private Date userbirthday;

    public Integer getUserid() {
        return userid;
    }

    public void setUserid(Integer userid) {
        this.userid = userid;
    }

    public String getUsername() {
        return username;
    }

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

    public String getUseraddress() {
        return useraddress;
    }

    public void setUseraddress(String useraddress) {
        this.useraddress = useraddress;
    }

    public String getUsersex() {
        return usersex;
    }

    public void setUsersex(String usersex) {
        this.usersex = usersex;
    }

    public Date getUserbirthday() {
        return userbirthday;
    }

    public void setUserbirthday(Date userbirthday) {
        this.userbirthday = userbirthday;
    }

    @Override
    public String toString() {
        return "User{" +
                "userid=" + userid +
                ", username='" + username + '\'' +
                ", useraddress='" + useraddress + '\'' +
                ", usersex='" + usersex + '\'' +
                ", userbirthday=" + userbirthday +
                '}';
    }
}

第二步在dao 层配置语句

IAccountDao 代码
package com.itheima.dao;

import com.itheima.domain.Account;

import org.apache.ibatis.annotations.*;
import org.apache.ibatis.mapping.FetchType;

import java.util.List;

public interface IAccountDao {
    @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(property = "user",column = "uid",
            //调用语句 一对一方法
            one = @One(select = "com.itheima.dao.IUserDao.findById",fetchType = FetchType.EAGER)
            )
    })
    List<Account> finAll();
}
IUserDao 代码
package com.itheima.dao;

import com.itheima.domain.User;
import org.apache.ibatis.annotations.*;

import java.util.List;

public interface IUserDao {
    /**
     * 查找所有数据
     */
    @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> finAll();
    /*
     * 新增方法
     */
    @Insert("insert into user(username,address,sex,birthday) values(#{username},#{address},#{sex},#{birthday})")
    @ResultMap(value = {"userMap"})
    void  saveUser(User user);
    /**
     * 修改方法
     */
    @Update("update user set username=#{username},address=#{address},sex=#{sex},birthday=#{birthday} where id=#{id}")
    @ResultMap(value = {"userMap"})
    void updateUser(User user);

    /**
     * 删除方法
     */

    @Delete("delete from user where id =#{id}")
    @ResultMap(value = {"userMap"})
    void deleteUser(Integer userId);
    /**
     * 查询方法
     * @return
     */
    @Select("select * from User where id =#{id}")
    @ResultMap(value = {"userMap"})
    User findById(Integer userId);

    /**
     * 搜索方法
     */
    //第一种方法
    @Select("select * from User where username like #{username}")
    @ResultMap(value = {"userMap"})
    List<User> FindByNames(String username );
    //第二种方法不需要百分号
    @Select("select * from User where username like '%${values}%'")
    @ResultMap(value = {"userMap"})
    List<User> FindByNameOne(String username );
    /**
     * 查询总用户数
     */
    @Select("select count(*) from User")
    @ResultMap(value = {"userMap"})
    int findTotalUser();


}

 最后一步测试类调用

测试类代码

package com.itheima;

import com.itheima.dao.IAccountDao;
import com.itheima.dao.IUserDao;
import com.itheima.domain.Account;
import com.itheima.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.InputStream;
import java.util.List;

public class Accountest {
    private InputStream in;
    private SqlSession sqlSession;
    private IAccountDao AccountDao;

    @Before//用于在测试方法执行之前执行
    public void init()throws Exception{
        //1.读取配置文件,生成字节输入流
        in = Resources.getResourceAsStream("SqlMapConfig.xml");
        //2.获取SqlSessionFactory
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
        //3.获取SqlSession对象
        sqlSession = factory.openSession(true);
        //4.获取dao的代理对象
      AccountDao = sqlSession.getMapper(IAccountDao.class);
    }

    @After//用于在测试方法执行之后执行
    public void destroy()throws Exception{
        //提交事务
        sqlSession.commit();
        //6.释放资源
        sqlSession.close();
        in.close();
    }
    @Test
    public void findAll(){
        List<Account> accounts = AccountDao.finAll();
        for (Account account : accounts) {
            System.out.println(account);
            System.out.println(account.getUser());
        }


    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

成序原

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值