MyBatis 一对多 多对一关联 trim foreach

2018年1月15日 22:42:15


第一段课内容 trim

填充 where 去除and or

<trim prefix="where" prefixOverrides="and | or">

<if test="userName != null and userName != ''">
and userName like CONCAT ('%',#{userName},'%') 
</if>
<if test="userRole != null">
and userRole = #{userRole}
</if>

</trim>



第二段课内容

填充 set 末尾拼接where id = #{id} 末尾省略逗号

<trim prefix="set" suffix="where id = #{id}" suffixOverrides=",">

中间是if

<if test="userName != null">userName=#{userName},</if>

</trim>





第三段课内容

传入的集合类型 集合里每个元素 开始 分隔 结束 穿进来的值

<foreach collection="list" item="yuansu" open="(" separator="," close=")">#{yuansu}</foreach>








第四段课内容 多对一和一对多关联

一对多关联

<resultMap type="本类别名" id="父类方法名">

中间是本类基本属性

<id property="id" column="r.id"></id>
<result property="userCode" column="userCode"/>
<result property="userNmae" column="userNmae"/>

</resultMap>

<resultMap type="本类别名" id="子类方法名" extends="父类resultMap的id名">
本类里的声明的属性名books本类里声明的属性类型BOOK对方命名空间.resultMap的id名

<collection property="addresses" ofType="Address" resultMap="com.bdqn.dao.getAddress"></collection>
</resultMap>


查的时候就用子类id名






多对一关联

<resultMap type="本类别名" id="方法名">

中间是本类属性
<id property="id" column="r.id"></id>
<result property="userCode" column="userCode"/>
<result property="userNmae" column="userNmae"/>
<result property="userRole" column="userRole"/>
<!-- 一对一 关联 User要多一个属性-->

本类里声明的属性名books 本类里声明的属性类型BOOK
<association property="role" javaType="role">

对方属性名
<id property="id" column="rl_id"/>
<result property="roleCode" column="roleCode"/>
<result property="roleName" column="roleName"/>
</association>
</resultMap>












项目代码演示

第一步WebRoot\WEB-INF\lib里粘贴四个jar包添加依赖


第二步src里粘贴三个

database.properties

log4j.properties

mybatis-config.xml


最后一个配置一下 取类型别名 顺带加载dao包里的某个.xml


第三步 工具类 单例模式双重锁

package com.bdqn.utils;


import java.io.IOException;
import java.io.InputStream;


import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;


public class SqlSessionUtils {

//私有属性自己
private static SqlSessionUtils sqlSessionUtils;

//私有自己无参构造


//公有获得实例方法
public static synchronized SqlSessionUtils getInstance(){
if (sqlSessionUtils==null) {
synchronized (SqlSessionUtils.class) {
if (sqlSessionUtils==null) {
sqlSessionUtils=new SqlSessionUtils();
}
}
}
return sqlSessionUtils;
}

public SqlSession getSqlSession(){
SqlSession session=null;
try {
InputStream is=Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(is);
session = sqlSessionFactory.openSession(false);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return session;
}

public void closeSqlSession(SqlSession session){
if (session!=null) {
session.close();
}
}
}










第四步 三个实体类

第一个实体类

package com.bdqn.entity;


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


public class User implements Serializable{
private Integer id; //id 
private String userCode; //用户编码
private String userName; //用户名称
private String userPassword; //用户密码
private Integer gender;  //性别
private Date birthday;  //出生日期
private String phone;   //电话
private String address; //地址
private Integer userRole;    //用户角色ID
private Integer createdBy;   //创建者
private Date creationDate; //创建时间
private Integer modifyBy;     //更新者
private Date modifyDate;   //更新时间

private Integer age;//年龄
private String userRoleName; //用户角色名称

//关联接的set get
private Role role;
List<Address> addresses;



public List<Address> getAddresses() {
return addresses;
}


public void setAddresses(List<Address> addresses) {
this.addresses = addresses;
}


public Role getRole() {
return role;
}


public void setRole(Role role) {
this.role = role;
}


public void setAge(Integer age) {
this.age = age;
}


@Override
public String toString() {
return "User [id=" + id + ", userCode=" + userCode + ", userName="
+ userName + ", userPassword=" + userPassword + ", gender="
+ gender + ", birthday=" + birthday + ", phone=" + phone
+ ", address=" + address + ", userRole=" + userRole
+ ", createdBy=" + createdBy + ", creationDate=" + creationDate
+ ", modifyBy=" + modifyBy + ", modifyDate=" + modifyDate
+ ", age=" + age + ", userRoleName=" + userRoleName + "]";
}


public Integer getAge() {
/*long time = System.currentTimeMillis()-birthday.getTime();
Integer age = Long.valueOf(time/365/24/60/60/1000).IntegerValue();*/
Date date = new Date();
Integer age = date.getYear()-birthday.getYear();
return age;
}

public String getUserRoleName() {
return userRoleName;
}
public void setUserRoleName(String userRoleName) {
this.userRoleName = userRoleName;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUserCode() {
return userCode;
}
public void setUserCode(String userCode) {
this.userCode = userCode;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserPassword() {
return userPassword;
}
public void setUserPassword(String userPassword) {
this.userPassword = userPassword;
}
public Integer getGender() {
return gender;
}
public void setGender(Integer gender) {
this.gender = gender;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public Integer getUserRole() {
return userRole;
}
public void setUserRole(Integer userRole) {
this.userRole = userRole;
}
public Integer getCreatedBy() {
return createdBy;
}
public void setCreatedBy(Integer createdBy) {
this.createdBy = createdBy;
}
public Date getCreationDate() {
return creationDate;
}
public void setCreationDate(Date creationDate) {
this.creationDate = creationDate;
}
public Integer getModifyBy() {
return modifyBy;
}
public void setModifyBy(Integer modifyBy) {
this.modifyBy = modifyBy;
}
public Date getModifyDate() {
return modifyDate;
}
public void setModifyDate(Date modifyDate) {
this.modifyDate = modifyDate;
}
}



第二个实体类

package com.bdqn.entity;


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


public class Role implements Serializable{

private Integer id;   //id
private String roleCode; //角色编码
private String roleName; //角色名称
private Integer createdBy; //创建者
private Date creationDate; //创建时间
private Integer modifyBy; //更新者
private Date modifyDate;//更新时间

public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getRoleCode() {
return roleCode;
}
public void setRoleCode(String roleCode) {
this.roleCode = roleCode;
}
public String getRoleName() {
return roleName;
}
public void setRoleName(String roleName) {
this.roleName = roleName;
}
public Integer getCreatedBy() {
return createdBy;
}
public void setCreatedBy(Integer createdBy) {
this.createdBy = createdBy;
}
public Date getCreationDate() {
return creationDate;
}
public void setCreationDate(Date creationDate) {
this.creationDate = creationDate;
}
public Integer getModifyBy() {
return modifyBy;
}
public void setModifyBy(Integer modifyBy) {
this.modifyBy = modifyBy;
}
public Date getModifyDate() {
return modifyDate;
}
public void setModifyDate(Date modifyDate) {
this.modifyDate = modifyDate;
}

}



第三个实体类

package com.bdqn.entity;


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


public class Address implements Serializable{
private Integer id;//主键ID
private String postCode; //邮编
private String contact;//联系人
private String addressDesc;//地址
private String tel;//联系电话
private Integer createdBy; //创建者
private Date creationDate; //创建时间
private Integer modifyBy; //更新者
private Date modifyDate;//更新时间
private Integer userId;//用户ID

public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getPostCode() {
return postCode;
}
public void setPostCode(String postCode) {
this.postCode = postCode;
}
public String getContact() {
return contact;
}
public void setContact(String contact) {
this.contact = contact;
}
public String getAddressDesc() {
return addressDesc;
}
public void setAddressDesc(String addressDesc) {
this.addressDesc = addressDesc;
}
public String getTel() {
return tel;
}
public void setTel(String tel) {
this.tel = tel;
}
public Integer getCreatedBy() {
return createdBy;
}
public void setCreatedBy(Integer createdBy) {
this.createdBy = createdBy;
}
public Date getCreationDate() {
return creationDate;
}
public void setCreationDate(Date creationDate) {
this.creationDate = creationDate;
}
public Integer getModifyBy() {
return modifyBy;
}
public void setModifyBy(Integer modifyBy) {
this.modifyBy = modifyBy;
}
public Date getModifyDate() {
return modifyDate;
}
public void setModifyDate(Date modifyDate) {
this.modifyDate = modifyDate;
}


}






第五步 dao包两个接口

第一个 接口UserDao.java

package com.bdqn.dao;


import java.util.ArrayList;
import java.util.List;


import org.apache.ibatis.annotations.Param;


import com.bdqn.entity.User;


public interface UserDao {
List<User> getUserList(@Param("userName")String userName,@Param("userRole")Integer roleId);

int modify(User user);

List<User> getUserByRoledId_foreach_list(List<Integer> roleList);

List<User> getUserListLian(@Param("userRole")Integer roleId);

User getUserListYiDuiDUo(@Param("id")Integer userId);
}




第二个接口AddressDao.java

package com.bdqn.dao;


public interface AddressDao {

}








第六步 三个.xml文件


第一个xml文件UserMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">


<mapper namespace="com.bdqn.dao.UserDao">
<resultMap type="User" id="userList">
<result property="id" column="id"/>
<result property="userCode" column="userCode"/>
<result property="userName" column="userName"/>
<result property="phone" column="phone"/>
<result property="birthday" column="birthday"/>
<result property="gender" column="gender"/>
<result property="userRole" column="userRole"/>
<result property="userRoleName" column="roleName"/>
</resultMap>

<select id="getUserList" resultType="User">
select * from smbms_user
<!-- 填充去除-->
<trim prefix="where" prefixOverrides="and | or">
<if test="userName != null and userName != ''">
and userName like CONCAT ('%',#{userName},'%') 
</if>
<if test="userRole != null">
and userRole = #{userRole}
</if>
</trim>
</select>

<update id="modify" parameterType="User">
update smbms_user 
<!-- 填充set末尾拼接where id = #{id} 去除末的逗号-->
<trim prefix="set" suffix="where id = #{id}" suffixOverrides=",">
<if test="userCode != null">userCode=#{userCode},</if>
<if test="userName != null">userName=#{userName},</if>
<if test="userPassword != null">userPassword=#{userPassword},</if>
<if test="gender != null">gender=#{gender},</if>
<if test="birthday != null">birthday=#{birthday},</if>
<if test="phone != null">phone=#{phone},</if>
<if test="address != null">address=#{address},</if>
<if test="userRole != null">userRole=#{userRole},</if>
<if test="modifyBy != null">modifyBy=#{modifyBy},</if>
<if test="modifyDate != null">modifyDate=#{modifyDate},</if>
</trim>
</update>

<select id="getUserByRoledId_foreach_list" resultMap="userList">
select * from smbms_user where userRole in
<!-- 传进来的集合类型每个元素名 开始分割 结束 每个元素名-->
<foreach collection="list" item="yuansu" open="(" separator="," close=")">#{yuansu}</foreach>
</select>

<resultMap type="User" id="UserMap">
<id property="id" column="r.id"></id>
<result property="userCode" column="userCode"/>
<result property="userNmae" column="userNmae"/>
<result property="userRole" column="userRole"/>
<!-- 一对一 关联 User要多一个属性-->
<association property="role" javaType="role">
<id property="id" column="rl_id"/>
<result property="roleCode" column="roleCode"/>
<result property="roleName" column="roleName"/>
</association>
</resultMap>

<select id="getUserListLian" resultMap="UserMap" parameterType="int">
select u.*,r.id as rl_id,r.roleName from smbms_user u,smbms_role r where u.userRole=#{userRole} and u.userRole = r.id
</select>

<resultMap type="User" id="getUser">
<id property="id" column="id"/>
<result property="userCode" column="userCode"/>
<result property="userName" column="userName"/>
</resultMap>

<!-- 一对多 -->
<resultMap type="User" id="getUserAddressMap" extends="getUser">
<!-- 雷属性名类名 -->
<collection property="addresses" ofType="Address" resultMap="com.bdqn.dao.getAddress"></collection>
</resultMap>

<select id="getUserListYiDuiDUo" resultMap="getUserAddressMap" parameterType="int">
select u.*,a.id AS a_id,a.contact,a.addressDesc,a.postCode,a.tel,a.userId
from smbms_user u 
left join smbms_address a
on u.id = a.userId where u.id=#{id}
</select>
</mapper>






第二个xml文件AddressMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">


<mapper namespace="com.bdqn.dao">
<resultMap type="Address" id="getAddress">
<result property="postCode" column="postCode"/>
<result property="tel" column="tel"/>
<result property="contact" column="contact"/>
<result property="addressDesc" column="addressDesc"/>
</resultMap>
</mapper>




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Mybatis是一种Java的持久层框架,提供了多种功能强大的SQL语句拼接方式,trimforeach是其中两种常用的拼接方式。 trim元素可以在 SQL 语句拼接时,将多余的 SQL 片段去除,从而保证 SQL 语句的正确性。trim元素常用的属性有prefix、suffix、prefixOverrides和suffixOverrides。 而foreach元素则可以对一个集合进行遍历,并将集合中的元素作为参数传入到SQL语句中,从而实现批量操作。foreach元素常用的属性有collection、item、index、separator等。 下面以一个例子来介绍trimforeach的用法: 假设有一个需求是查询某个部门中员工的信息,但是查询条件可能有多个,比如姓名、年龄、性别等。我们可以使用trim元素对SQL语句进行拼接,如下所示: ``` <select id="queryEmployees" parameterType="map" resultType="Employee"> SELECT * FROM employee <trim prefix="WHERE" prefixOverrides="AND | OR "> <if test="name != null and name != ''"> AND name = #{name} </if> <if test="age != null and age != ''"> AND age = #{age} </if> <if test="gender != null and gender != ''"> AND gender = #{gender} </if> </trim> </select> ``` 上述代码中,我们使用了trim元素来拼接SQL语句中的WHERE关键字和多余的AND或OR关键字,从而保证SQL语句的正确性。 而如果我们需要查询多个员工信息,可以使用foreach元素对员工id集合进行遍历,如下所示: ``` <select id="queryEmployeesByIds" parameterType="list" resultType="Employee"> SELECT * FROM employee WHERE id IN <foreach item="id" collection="ids" open="(" separator="," close=")"> #{id} </foreach> </select> ``` 上述代码中,我们使用了foreach元素来遍历员工id集合,并将集合中的每个元素作为参数传入到SQL语句中的IN条件中,从而实现批量操作。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值