MyBatis学习笔记(二)之关联关系

网友投稿 186 2023-07-21


MyBatis学习笔记(二)之关联关系

今天主要学习的关联关系是一对一关系与一对多关系。

一、一对一关系

还是通过例子来解释说明。(一个妻子对应一个丈夫)。

1)数据库信息

create table t_wife(

id int primary key auto_increment,

wife_name varchar(),

fk_husband_id int

);

create table t_husband(

id int primary key auto_increment,

husband_name varchar()

);

insert into t_husband values (null,'hello');

insert into t_wife values(null,'kitty',)

2)对应的javaBean代码

虽然在数据库里只有一方配置的外键,但是这个一对一是双向的关系。

HusbandBean.java

package com.cy.mybatis.beans;

import java.io.Serializable;

/**

* one to one

* @author acer

*

*/

public class HusbandBean implements Serializable{

private static final long serialVersionUID = L;

private Integer id;

private String name;

private WifeBean wife;

public HusbandBean() {

super();

}

public HusbandBean(Integer id, String name, WifeBean wife) {

super();

this.id = id;

this.name = name;

this.wife = wife;

}

public Integer getId() {

return id;

}

public void setId(Integer id) {

this.id = id;

}

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

public WifeBean getWife() {

return wife;

}

public void setWife(WifeBean wife) {

this.wife = wife;

}

@Override

public String toString() {

return "Husband [id=" + id + ", name=" + name + ", wife=" + wife + "]";

}

}

WifeBean.java

package com.cy.mybatis.beans;

import java.io.Serializable;

/**

* one to one

* @author acer

*

*/

public class WifeBean implements Serializable{

private static final long serialVersionUID = L;

private Integer id;

private String name;

private HusbandBean husband;

public WifeBean() {

super();

}

public WifeBean(Integer id, String name, HusbandBean husband) {

super();

this.id = id;

this.name = name;

this.husband = husband;

}

public Integer getId() {

return id;

}

public void setId(Integer id) {

this.id = id;

}

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

public HusbandBean getHusband() {

return husband;

}

public void setHusband(HusbandBean husband) {

this.husband = husband;

}

@Override

public String toString() {

return "Wife [id=" + id + ", name=" + name + ", husband=" + husband

+ "]";

}

}

3)接下来建立两个接口,HusbandMapper,WifeMapper.

HusbandMapper

package com.cy.mybatis.mapper;

import com.cy.mybatis.beans.HusbandBean;

public interface HusbandMapper {

/**

* 根据id查询丈夫信息

* @param id

* @return

* @throws Exception

*/

public HusbandBean selectHusbandById (int id) throws Exception;

/**

* 根据id查询丈夫与妻子信息

* @param id

* @return

* @throws Exception

*/

public HusbandBean selectHusbandAndWife(int id) throws Exception;

}

4)定义HusbandMapper.xml文件

select * from t_husband where id=#{id}

select * from t_husband where id=#{id}

在WifeMapper.xml里有个方法

select * from t_wife where fk_husband_id = #{id}

5)写个实现

package com.cy.mybatis.service;

import org.apache.ibatis.session.SqlSession;

import com.cy.mybatis.beans.HusbandBean;

import com.cy.mybatis.mapper.HusbandMapper;

import com.cy.mybatis.tools.DBTools;

public class OneToOneService {

public static void main(String[] args) {

selectHusbandAndWife();

}

private static void selectHusbandAndWife() {

SqlSession session = DBTools.getSession();

HusbandMapper hm = session.getMapper(HusbandMapper.class);

try {

HusbandBean husband = hm.selectHusbandAndWife();

System.out.println(husband);

session.commit();

} catch (Exception e) {

e.printStackTrace();

}

}

}

注意:那个工具类还是前一章那样写的,就相当与在昨天的基础上建立的。

注意:

mybatis实际是对XML进行操作,我们所有的方法都直接定义在XML中,写个接口只是为了更好的符合我们3层的思想,如果不写接口,直接通过session也可以直接操作xml中的方法 ,

XML中只要有方法,就可以使用,而调用的方式就是:namespace+方法名;

例外使用resultType时,一定要保证,你属性名与字段名相同;

如果不相同,就使用resultMap 。

二、一对多关系

还是通过例子来解释说明。(一把锁对应多把钥匙)。

2.1)数据库信息 这里没有添加数据了,我们用批量添加数据

create table t_key(

id int primary key auto_increment,

key_name varchar(),

fk_lock_id int

);

create table t_lock(

id int primary key auto_increment,

lock_name varchar()

);

2.2) 实体类

KeyBean.java

package com.cy.mybatis.beans;

import java.io.Serializable;

/**

* manyTOone

*

*

*/

public class KeyBean implements Serializable {

private static final long serialVersionUID = L;

private Integer id;

private String key;

private LockBean lock;

public KeyBean() {

super();

}

public KeyBean(Integer id, String key, LockBean lock) {

super();

this.id = id;

this.key = key;

this.lock = lock;

}

public Integer getId() {

return id;

}

public void setId(Integer id) {

this.id = id;

}

public String getKey() {

return key;

}

public void setKey(String key) {

this.key = key;

}

public LockBean getLock() {

return lock;

}

public void setLock(LockBean lock) {

this.lock = lock;

}

@Override

public String toString() {

return "KeyBean [id=" + id + ", key=" + key + ", lock=" + lock + "]";

}

}

LockBean.java

package com.cy.mybatis.beans;

import java.io.Serializable;

import java.util.List;

/**

* oneTOmany

*

*

*/

public class LockBean implements Serializable{

private static final long serialVersionUID = L;

private Integer id;

private String lock;

private List keys;

public LockBean() {

super();

}

public LockBean(Integer id, String lock, List keys) {

super();

this.id = id;

this.lock = lock;

this.keys = keys;

}

public Integer getId() {

return id;

}

public void setId(Integer id) {

this.id = id;

}

public String getLock() {

return lock;

}

public void setLock(String lock) {

this.lock = lock;

}

public List getKeys() {

return keys;

}

public void setKeys(List keys) {

this.keys = keys;

}

@Override

public String toString() {

return "LockBean [id=" + id + ", keys=" + keys + ", lock=" + lock + "]";

}

}

2.3) 建立接口

KeyMapper.java

package com.cy.mybatis.mapper;

import java.util.List;

import org.apache.ibatis.annotations.Param;

import com.cy.mybatis.beans.KeyBean;

public interface KeyMapper {

/**

* 批量添加钥匙

* @return

* 提倡 这样使用 @Param("keys")

*/

public int batchSaveKeys(@Param("keys")List keys);

}

LockMapper.java

package com.cy.mybatis.mapper;

import org.apache.ibatis.annotations.Param;

import com.cy.mybatis.beans.LockBean;

public interface LockMapper {

/**

* 添加锁

* @param lock

* @return

*/

public int saveLock(@Param("lock")LockBean lock);

/**

* 根据ID查询锁的资料

* @param id

* @return

*/

public LockBean findLockById(int id);

/**

* 根据ID查询锁与钥匙的资料

* onemany

* @param id

* @return

*/

public LockBean findLockAndKeys(int id);

}

2.4) 建立xml文件

KeyMapper.xml

insert into t_key values

(null,#{key.key},#{key.lock.id})

select * from t_key where fk_lock_id = #{id}

LockMapper.xml

insert into t_lock values (null,#{lock.lock})

select * from t_lock where id= #{id}

select * from t_lock where id= #{id}

2.5 ) 实现

package com.cy.mybatis.service;

import java.util.ArrayList;

import java.util.List;

import org.apache.ibatis.session.SqlSession;

import com.cy.mybatis.beans.KeyBean;

import com.cy.mybatis.beans.LockBean;

import com.cy.mybatis.mapper.KeyMapper;

import com.cy.mybatis.mapper.LockMapper;

import com.cy.mybatis.tools.DBTools;

public class OneToManyService {

public static void main(String[] args) {

// saveLock();

// batchSaveKeys();

findLockAndKeys();

}

private static void findLockAndKeys() {

SqlSession session = DBTools.getSession();

LockMapper lm = session.getMapper(LockMapper.class);

LockBean lock = lm.findLockAndKeys();

System.out.println(lock);

}

private static void batchSaveKeys() {

SqlSession session = DBTools.getSession();

LockMapper lm = session.getMapper(LockMapper.class);

KeyMapper km = session.getMapper(KeyMapper.class);

LockBean lock = lm.findLockById();

List keys = new ArrayList();

for(int i = ; i < ; i++){

KeyBean key = new KeyBean(null, "钥匙"+i, lock);

keys.add(key);

}

km.batchSaveKeys(keys);

session.commit();

}

private static void saveLock() {

SqlSession session = DBTools.getSession();

LockMapper lm = session.getMapper(LockMapper.class);

LockBean lock = new LockBean(null, "锁", null);

lm.saveLock(lock);

session.commit();

}

}

结果显示:

三 、批量操作与分页

这里就使用前一章的User.就写出主要的代码。

首先定义分页对象。

package com.cy.mybatis.beans;

import java.util.List;

/**

* 定义一个分页对象

*

* @author

*

*/

public class Pager {

private int pageNo;// 当前页码

private int pageTotal;// 总页码

private int rowsTotal;// 总条数

private int pageSize;// 每页显示条数

private List list;// 返回的数据集合

public int getPageNo() {

return pageNo;

}

public void setPageNo(int pageNo) {

this.pageNo = pageNo;

}

public int getPageTotal() {

return pageTotal;

}

public void setPageTotal(int pageTotal) {

this.pageTotal = pageTotal;

}

public int getRowsTotal() {

return rowsTotal;

}

public void setRowsTotal(int rowsTotal) {

this.rowsTotal = rowsTotal;

pageTotal = rowsTotal % pageSize == ? rowsTotal / pageSize : rowsTotal / pageSize + ;

}

public int getPageSize() {

return pageSize;

}

public void setPageSize(int pageSize) {

this.pageSize = pageSize;

}

public List> getList() {

return list;

}

public void setList(List list) {

this.list = list;

}

@Override

public String toString() {

return "Pager [pageNo=" + pageNo + ", pageTotal=" + pageTotal

+ ", rowsTotal=" + rowsTotal + ", pageSize=" + pageSize

+ ", list=" + list + "]";

}

}

UserMapper.java接口。

package com.cy.mybatis.mapper;

import java.util.List;

import java.util.Map;

import org.apache.ibatis.annotations.Param;

import com.cy.mybatis.beans.UserBean;

public interface UserMapper {

/**

* 新增用戶

* @param user

* @return

* @throws Exception

*/

public int insertUser(@Param("user")UserBean user) throws Exception;

/**

* 修改用戶

* @param user

* @param id

* @return

* @throws Exception

*/

public int updateUser (@Param("u")UserBean user,@Param("id")int id) throws Exception;

/**

* 刪除用戶

* @param id

* @return

* @throws Exception

*/

public int deleteUser(int id) throws Exception;

/**

* 根据id查询用户信息

* @param id

* @return

* @throws Exception

*/

public UserBean selectUserById(int id) throws Exception;

/**

* 查询所有的用户信息

* @return

* @throws Exception

*/

public List selectAllUser() throws Exception;

/**

* 批量增加

* @param user

* @return

* @throws Exception

*/

public int batchInsertUser(@Param("users")List user) throws Exception;

/**

* 批量删除

* @param list

* @return

* @throws Exception

*/

public int batchDeleteUser(@Param("list")List list) throws Exception;

/**

* 分页查询数据

* @param parma

* @return

* @throws Exception

*/

public List pagerUser(Map parmas) throws Exception;

/**

*

* 分页统计数据

* @param parma

* @return

* @throws Exception

*/

public int countUser(Map parmas) throws Exception;

}

xml文件

insert into t_user (username,password,account) values (#{user.username},#{user.password},#{user.account})

update t_user set username=#{u.username},password=#{u.password},account=#{u.account} where id=#{id}

delete from t_user where id=#{id}

select * from t_user where id=#{id}

select * from t_user

insert into t_user values

(null,#{users.username},#{users.password},#{users.account})

delete from t_user where id in (

#{id}

)

select * from t_user where =

and username like '%${username}%'

limit ${index},${pageSize}

select count(*) from t_user where =

and username like '%${username}%'

#在生成SQL时,对于字符类型参数,会拼装引号

$在生成SQL时,不会拼装引号,可用于order by之类的参数拼装

测试类

package com.cy.mybatis.service;

import java.util.ArrayList;

import java.util.HashMap;

import java.util.List;

import java.util.Map;

import org.apache.ibatis.session.SqlSession;

import com.cy.mybatis.beans.UserBean;

import com.cy.mybatis.tools.DBTools;

import com.cy.mybatis.mapper.UserMapper;

public class UserService {

/**

* @param args

*/

public static void main(String[] args) {

// insertUser();

// deleteUser();

// updateUser();

// selectUserById();

// selectAllUser();

// batchInsertUser();

// batchDeleteUser();

// countUser();

pagerUser();

}

private static void countUser() {

SqlSession session = DBTools.getSession();

UserMapper mapper = session.getMapper(UserMapper.class);

Map params = new HashMap();

params.put("username", "kitty");

int index = ;

params.put("index", index);//从第几页开始。mysql是从开始的

params.put("pageSize", );//每页显示的数据条数

int count;

try {

count = mapper.countUser(params);

System.out.println(count);

} catch (Exception e) {

e.printStackTrace();

}

}

private static void pagerUser() {

SqlSession session = DBTools.getSession();

UserMapper mapper = session.getMapper(UserMapper.class);

Map params = new HashMap();

params.put("username", "kitty");

params.put("index", );//从第几页开始。mysql是从开始的

params.put("pageSize", );//每页显示的数据条数

try {

List u = mapper.pagerUser(params);

for (UserBean userBean : u) {

System.out.println("--------"+userBean);

}

} catch (Exception e) {

e.printStackTrace();

}

}

private static void batchDeleteUser() {

SqlSession session = DBTools.getSession();

UserMapper mapper = session.getMapper(UserMapper.class);

List ids = new ArrayList();

for(int i = ; i < ; i ++){

ids.add(i);

}

try {

mapper.batchDeleteUser(ids);

session.commit();

} catch (Exception e) {

e.printStackTrace();

}

}

private static void batchInsertUser() {

SqlSession session = DBTools.getSession();

UserMapper mapper = session.getMapper(UserMapper.class);

List users = new ArrayList();

for(int i = ; i < ; i ++){

UserBean user = new UserBean("kitty"+i, "", .);

users.add(user);

}

try {

mapper.batchInsertUser(users);

session.commit();

} catch (Exception e) {

e.printStackTrace();

}

}

/**

* 新增用户

*/

private static void insertUser() {

SqlSession session = DBTools.getSession();

UserMapper mapper = session.getMapper(UserMapper.class);

UserBean user = new UserBean("懿", "", .);

try {

mapper.insertUser(user);

System.out.println(user.toString());

session.commit();

} catch (Exception e) {

e.printStackTrace();

session.rollback();

}

}

/**

* 删除用户

*/

private static void deleteUser(){

SqlSession session=DBTools.getSession();

UserMapper mapper=session.getMapper(UserMapper.class);

try {

mapper.deleteUser();

session.commit();

} catch (Exception e) {

e.printStackTrace();

session.rollback();

}

}

/**

* 修改用户数据

*/

private static void updateUser(){

SqlSession session=DBTools.getSession();

UserMapper mapper=session.getMapper(UserMapper.class);

UserBean user =new UserBean("小明", "",.);

try {

mapper.updateUser(user, );

session.commit();

} catch (Exception e) {

e.printStackTrace();

session.rollback();

}

}

/**

* 根据id查询用户

*/

private static void selectUserById(){

SqlSession session=DBTools.getSession();

UserMapper mapper=session.getMapper(UserMapper.class);

try {

UserBean user= mapper.selectUserById();

System.out.println(user.toString());

session.commit();

} catch (Exception e) {

e.printStackTrace();

session.rollback();

}

}

/**

* 查询所有的用户

*/

private static void selectAllUser(){

SqlSession session=DBTools.getSession();

UserMapper mapper=session.getMapper(UserMapper.class);

try {

List user=mapper.selectAllUser();

System.out.println(user.toString());

session.commit();

} catch (Exception e) {

e.printStackTrace();

session.rollback();

}

}

}

看一下项目的整体:

每件事都需要坚持!


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:使用 Java8 实现观察者模式的方法(下)
下一篇:Struts2 自定义下拉框Tag标签
相关文章

 发表评论

暂时没有评论,来抢沙发吧~