Java进阶知识35 mybatis+Oracle 单向一对多关联 之CRUD操作【xml 版】
本文知识点(目录):
1、导读
1.1、技术概述
1.2、本文使用的jar包、项目结构图
2、本文所有代码(xml版)
2.1、数据库脚本(oracle.sql)
2.2、mybatis.xml 核心配置文件
2.3、MyBatisUtils 工具类(用于连接数据库)
2.4、实体类(Team、Member )以及对应的xxxxxMapper.xml 配置文件
2.5、DAO层(Team类对应的接口及接口实现类、Member类对应的接口及接口实现类 )
2.6、测试类 (TestMemberDao)及测试结果
1、导读
a.本文使用的是Oracle+mybatis框架,单向一对多关联,以Member为主;(数据表之间的关系:team是主表,member是从表)
b.实现了CURD等操作:新增、修改、删除、批量删除、查询全部、多条件查询、根据id查询、查询某个团队下的所有成员。
c.本文只测试/演示DAO层与数据库之间的连接以及数据的CRUD操作
d.本项目的使用环境:MyEclipse10.7 + JDK1.8 + Oracle11g + mybatis3.1.1
2、本文所有代码(xml版)
1 -- 一对多 2 -- 1、创建表 3 create table team(-- 团队表 4 id number(5) primary key, 5 name varchar2(20), 6 description varchar2(50) 7 ); 8 9 create table member(-- 成员表 10 id number(5) primary key, 11 name varchar2(20), 12 sex smallint, -- 用number(1)也行,0代表男,1代表女 13 team_id number(5), 14 constraint member_team_fk foreign key(team_id) references team(id) 15 ); 16 17 -- 2、创建序列 18 create sequence team_seq 19 minvalue 1 --最小值 20 maxvalue 99999 -- 最大值 21 increment by 1 --从1开始计数 22 start with 1 --每次加1 23 nocycle --一直累加,不循环 24 nocache; --不建缓冲区。 25 26 create sequence member_seq 27 minvalue 1 28 maxvalue 99999 29 increment by 1 30 start with 1 31 nocycle 32 nocache; 33 34 -- 3、创建触发器 35 create or replace trigger team_tg 36 before insert on team for each row 37 begin 38 select team_seq.Nextval into:new.id from dual; 39 end; 40 41 create or replace trigger member_tg 42 before insert on member for each row 43 begin 44 select member_seq.Nextval into:new.id from dual; 45 end; 46 47
1 <?xml version="1.0" encoding="UTF-8" ?> 2 <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" 3 "http://mybatis.org/dtd/mybatis-3-config.dtd"> 4 <configuration> 5 <environments default="development"> 6 <environment id="development"> 7 <transactionManager type="JDBC" /> 8 <dataSource type="POOLED"> 9 <property name="driver" value="oracle.jdbc.driver.OracleDriver" /> 10 <property name="url" value="jdbc:oracle:thin:@localhost:1521:shoreid" /> 11 <property name="username" value="zhangsan" /> 12 <property name="password" value="123456" /> 13 </dataSource> 14 </environment> 15 </environments> 16 17 <mappers><!-- 5、通过SqlSession对象读取XXXXXMapper.xml映射文件中的对应操作id,从而获取sql语句; --> 18 <mapper resource="com/shore/o2m/entity/MemberMapper.xml"/> 19 <mapper resource="com/shore/o2m/entity/TeamMapper.xml"/> 20 </mappers> 21 </configuration>
1 package com.shore.common.utils; 2 3 import java.io.Reader; 4 5 import org.apache.ibatis.io.Resources; 6 import org.apache.ibatis.session.SqlSession; 7 import org.apache.ibatis.session.SqlSessionFactory; 8 import org.apache.ibatis.session.SqlSessionFactoryBuilder; 9 10 /** 11 * @author DSHORE/2020-3-12 12 * 13 */ 14 public class MyBatisUtils { 15 private static ThreadLocal<SqlSession> threadLocal = new ThreadLocal<SqlSession>(); 16 private static SqlSessionFactory sqlSessionFactory; 17 18 static{ 19 try { 20 //1、读取配置 21 Reader reader = Resources.getResourceAsReader("mybatis.xml"); 22 //2、创建SqlSessionFactory 23 sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader); 24 } catch (Exception e) { 25 e.fillInStackTrace(); 26 throw new RuntimeException(e); 27 } 28 } 29 30 private MyBatisUtils() { } 31 32 //3、获取SqlSession 33 public static SqlSession getSqlSession(){ 34 SqlSession sqlSession = threadLocal.get(); 35 if (sqlSession == null) {//如果上面获取不到SQLSession,将通过下面的方式来获取 36 sqlSession = sqlSessionFactory.openSession(); 37 } 38 return sqlSession; 39 } 40 41 //7、关闭SqlSession 42 public static void closeSqlSession() { 43 SqlSession sqlSession = threadLocal.get(); 44 if (sqlSession != null) { 45 sqlSession.close(); 46 threadLocal.remove(); 47 } 48 } 49 }
2.4、实体类(Team、Member)以及对应的xxxxxMapper.xml 配置文件
Team.java
1 package com.shore.o2m.entity; 2 3 import java.util.Set; 4 5 /** 6 * @author DSHORE/2020-3-17 7 * mybatis:单向一对多,以Member为主 8 * team表与member表之间的关系:team是主表,member是从表 9 */ 10 public class Team {// 一的一方 11 private Integer id; 12 private String name; 13 private String description; 14 private Set<Member> members; 15 16 //省略Setters和Getters方法 17 }
TeamMapper.xml 配置文件
1 <?xml version="1.0" encoding="UTF-8" ?> 2 <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" 3 "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> 4 5 <mapper namespace="teamNameSpace"> 6 <resultMap id="teamResultMap" type="com.shore.o2m.entity.Team"> 7 <id property="id" column="id" /> <!-- property和 column不能省略 --> 8 <result property="name" column="name" /> 9 <result property="description" column="description" /> 10 <!-- 单向一对多关联,以Member为主,一的一方 --> 11 <collection property="members" resultMap="memberNameSpace.memberResultMap"></collection> 12 </resultMap> 13 14 <!--======================= 新增 ============================= --> 15 <insert id="addTeam" parameterType="com.shore.o2m.entity.Team"> 16 <!-- 返回当前,刚刚插入的数据的id,用于member表的外键team_id --> 17 <selectKey order="AFTER" keyProperty="id" resultType="int"> 18 <!-- 这里的id是自增长的(序列+触发器),具体请看oracle.sql中的数据表脚本 --> 19 select max(id) as id from team 20 <!-- select team_seq.Nextval as id from dual --> 21 </selectKey> 22 insert into team(name,description) 23 values(#{name,jdbcType=VARCHAR},#{description,jdbcType=VARCHAR}) 24 </insert> 25 26 <!--===================== 根据id查询 ========================== --> 27 <select id="findById" parameterType="int" resultMap="teamResultMap"> 28 select * from team where id = #{id,jdbcType=NUMERIC} 29 </select> 30 31 <!--====================== 查询所有 =========================== --> 32 <select id="selectAll" resultMap="teamResultMap"> 33 select * from team 34 </select> 35 </mapper>
Member.java
1 package com.shore.o2m.entity; 2 3 /** 4 * @author DSHORE/2020-3-17 5 * mybatis:单向一对多,以Member为主 6 * team表与member表之间的关系:team是主表,member是从表 7 */ 8 public class Member { 9 private Integer id; 10 private String name; 11 private Integer sex; 12 private Team team; 13 14 //省略Setters和Getters方法 15 16 @Override 17 public String toString() { 18 return "Member [id=" + id + ", name=" + name + ", sex=" + sex 19 + ", team=" + team + "]"; 20 } 21 }
MemberMapper.xml 配置文件
1 <?xml version="1.0" encoding="UTF-8" ?> 2 <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" 3 "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> 4 5 <mapper namespace="memberNameSpace"> 6 <resultMap id="memberResultMap" type="com.shore.o2m.entity.Member"> 7 <id property="id" column="id"/> <!-- property和 column不能省略--> 8 <result property="name" column="name"/> 9 <result property="sex" column="sex"/> 10 <!-- 单向一对多关联,以Member为主,多的一方 --> 11 <association property="team" column="team_id" resultMap="teamNameSpace.teamResultMap"/> 12 </resultMap> 13 14 <!--======================= 新增 ============================= --> 15 <insert id="addMember" parameterType="com.shore.o2m.entity.Member"> 16 insert into member(name,sex,team_id) 17 values(#{name,jdbcType=VARCHAR},#{sex,jdbcType=NUMERIC},#{team.id,jdbcType=NUMERIC}) 18 </insert> 19 20 <!--======================= 修改 ============================= --> 21 <update id="updateMember" parameterType="com.shore.o2m.entity.Member"> 22 update member 23 set 24 <if test="name != null"> 25 name=#{name,jdbcType=VARCHAR}, 26 </if> 27 <if test="sex != null"> 28 sex=#{sex,jdbcType=NUMERIC}, 29 </if> 30 <if test="team.id != null"> 31 team_id=#{team.id,jdbcType=NUMERIC} 32 </if> 33 where id=#{id,jdbcType=NUMERIC} 34 </update> 35 36 <!--===================== 根据id查询 =========================== --> 37 <select id="findById" parameterType="int" resultMap="memberResultMap"> 38 select m.*,t.* 39 from member m,team t 40 where m.team_id = t.id and m.id = #{id} 41 </select> 42 43 <!--===================== 多条件查询=========================== --> 44 <!-- resultMap和 parameterType的区别: 45 如果用resultMap="memberResultMap";则,member表以及关联表team中的数据都查询出来。 46 如果用parameterType="com.shore.o2m.entity.Member";则,查询结果只有member表的数据,team表为null。 47 --> 48 <select id="multiconditionalQuery" parameterType="map" resultMap="memberResultMap"> 49 select m.*,t.* from member m,team t 50 <where> 51 and m.team_id = t.id 52 <if test="memberName != null"> 53 and m.name = #{memberName} 54 </if> 55 <if test="teamName != null"> 56 and t.name = #{teamName} 57 </if> 58 </where> 59 </select> 60 61 <!--================== 查询指定战队下,所有队员 ==================== --> 62 <select id="selectAll" parameterType="String" resultMap="memberResultMap"> 63 select m.*,t.* 64 from member m,team t 65 where m.team_id = t.id and t.name = #{teamName} 66 </select> 67 68 <!--======================== 删除 ============================== --> 69 <delete id="deleteByMemberId" parameterType="int"> 70 delete from member where id=#{id} 71 </delete> 72 73 <!--======================= 批量删除 ============================ --> 74 <delete id="batchDeleteById"> 75 delete from member where id in 76 <foreach item="ids" collection="list" open="(" separator="," close=")"> 77 #{ids} 78 </foreach> 79 </delete> 80 </mapper>
2.5、DAO层(Team类对应的接口及接口实现类、Member类对应的接口及接口实现类 )
ITeamDao.java(接口类)
1 package com.shore.o2m.dao; 2 3 import java.util.List; 4 5 import com.shore.o2m.entity.Team; 6 7 /** 8 * @author DSHORE/2020-3-17 9 * 10 */ 11 public interface ITeamDao { 12 public int addTeam(Team team);//新增 13 14 public Team findByTeamId(int id);//根据id查询 15 16 public List<Team> listAll();//查询所有团队/战队 17 }
TeamDao.java (接口类ITeamDao的实现类)
1 package com.shore.o2m.dao.impl; 2 3 import java.util.ArrayList; 4 import java.util.List; 5 6 import org.apache.ibatis.session.SqlSession; 7 8 import com.shore.common.utils.MyBatisUtils; 9 import com.shore.o2m.dao.ITeamDao; 10 import com.shore.o2m.entity.Team; 11 12 /** 13 * @author DSHORE/2020-3-17 14 * 15 */ 16 public class TeamDao implements ITeamDao { 17 SqlSession sqlSession = null; 18 19 @Override //新增 20 public int addTeam(Team team) { 21 sqlSession = MyBatisUtils.getSqlSession(); 22 try { 23 return sqlSession.insert("teamNameSpace.addTeam", team); 24 } catch (Exception e) { 25 sqlSession.rollback();//如果出现异常,则,事务回滚 26 System.out.println(e.getMessage());//打印异常信息 27 } finally { 28 sqlSession.commit();//提交事务 29 MyBatisUtils.closeSqlSession();//关闭SqlSession 30 } 31 return 0; 32 } 33 34 @Override //根据id查询 35 public Team findByTeamId(int id) { 36 List<Team> teams = new ArrayList<Team>(); 37 Team team = null; 38 sqlSession = MyBatisUtils.getSqlSession(); 39 try { 40 teams = sqlSession.selectList("teamNameSpace.findById",id); 41 if (teams != null && teams.size() > 0) { 42 team = teams.get(0); 43 } 44 } catch (Exception e) { 45 System.out.println(e.getMessage()); 46 } finally { 47 MyBatisUtils.closeSqlSession(); 48 } 49 return team; 50 } 51 52 @Override //查询所有团队/战队 53 public List<Team> listAll() { 54 List<Team> teams = new ArrayList<Team>(); 55 sqlSession = MyBatisUtils.getSqlSession(); 56 try { 57 teams = sqlSession.selectList("teamNameSpace.selectAll"); 58 } catch (Exception e) { 59 System.out.println("error:" + e.getMessage()); 60 } finally { 61 MyBatisUtils.closeSqlSession(); 62 } 63 return teams; 64 } 65 }
IMemberDao.java(接口类)
1 package com.shore.o2m.dao; 2 3 import java.util.List; 4 5 import com.shore.o2m.entity.Member; 6 7 8 /** 9 * @author DSHORE/2020-3-17 10 * 11 */ 12 public interface IMemberDao { 13 public int addMember(Member member);//新增 14 15 public int updateMember(Member member);//修改 16 17 public Member findByMemberId(int id);//根据id查询 18 19 public List<Member> multiconditionalQuery(String teamName, String memberName);//多条件查询 20 21 public List<Member> listAllByTeam(String teamName);//查询指定战队下,所有队员 22 23 public int deleteMember(int id);//删除 24 25 public int batchDeleteById(List<Integer> ids);//批量删除 26 }
MemberDao.java(接口类IMemberDao的实现类)
1 package com.shore.o2m.dao.impl; 2 3 import java.util.ArrayList; 4 import java.util.HashMap; 5 import java.util.List; 6 import java.util.Map; 7 8 import org.apache.ibatis.session.SqlSession; 9 10 import com.shore.common.utils.MyBatisUtils; 11 import com.shore.o2m.dao.IMemberDao; 12 import com.shore.o2m.entity.Member; 13 14 /** 15 * @author DSHORE/2020-3-17 16 * 17 */ 18 public class MemberDao implements IMemberDao { 19 20 @Override //新增 21 public int addMember(Member member) { 22 SqlSession sqlSession = MyBatisUtils.getSqlSession(); 23 try { 24 return sqlSession.insert("memberNameSpace.addMember", member); 25 } catch (Exception e) { 26 sqlSession.rollback();//如果出现异常,则,事务回滚 27 System.out.println(e.getMessage());//打印异常信息 28 } finally { 29 sqlSession.commit();//提交事务 30 MyBatisUtils.closeSqlSession();//关闭SqlSession 31 } 32 return 0; 33 } 34 35 @Override //修改 36 public int updateMember(Member member) { 37 SqlSession sqlSession = MyBatisUtils.getSqlSession(); 38 try { 39 return sqlSession.insert("memberNameSpace.updateMember", member); 40 } catch (Exception e) { 41 sqlSession.rollback(); 42 System.out.println(e.getMessage()); 43 } finally { 44 sqlSession.commit(); 45 MyBatisUtils.closeSqlSession(); 46 } 47 return 0; 48 } 49 50 @Override //根据id查询 51 public Member findByMemberId(int id) { 52 List<Member> members = new ArrayList<Member>(); 53 Member member = null; 54 SqlSession sqlSession = MyBatisUtils.getSqlSession(); 55 try { 56 members = sqlSession.selectList("memberNameSpace.findById",id); 57 if (members != null && members.size() > 0) { 58 member = members.get(0); 59 } 60 } catch (Exception e) { 61 System.out.println(e.getMessage());//打印错误/异常信息 62 } finally { 63 MyBatisUtils.closeSqlSession();//关闭SqlSession 64 } 65 return member; 66 } 67 68 @Override //多条件查询 69 public List<Member> multiconditionalQuery(String teamName, String memberName) { 70 List<Member> members = new ArrayList<Member>(); 71 SqlSession sqlSession = MyBatisUtils.getSqlSession(); 72 try { 73 Map<String, String> map = new HashMap<String, String>(); 74 map.put("teamName", teamName); 75 map.put("memberName", memberName); 76 members = sqlSession.selectList("memberNameSpace.multiconditionalQuery", map); 77 } catch (Exception e) { 78 System.out.println("error:" + e.getMessage()); 79 } finally { 80 MyBatisUtils.closeSqlSession(); 81 } 82 return members; 83 } 84 85 @Override //查询指定战队下,所有队员 86 public List<Member> listAllByTeam(String teamName) { 87 List<Member> members = new ArrayList<Member>(); 88 SqlSession sqlSession = MyBatisUtils.getSqlSession(); 89 try { 90 members = sqlSession.selectList("memberNameSpace.selectAll",teamName); 91 } catch (Exception e) { 92 System.out.println(e.getMessage());//打印错误/异常信息 93 } finally { 94 MyBatisUtils.closeSqlSession();//关闭SqlSession 95 } 96 return members; 97 } 98 99 @Override //删除(只删除member表的消息,不删除关联表team的消息) 100 public int deleteMember(int id) { 101 SqlSession sqlSession = MyBatisUtils.getSqlSession(); 102 try { 103 return sqlSession.delete("memberNameSpace.deleteByMemberId", id); 104 } catch (Exception e) { 105 sqlSession.rollback(); 106 System.out.println(e.getMessage()); 107 } finally { 108 sqlSession.commit(); 109 MyBatisUtils.closeSqlSession(); 110 } 111 return 0; 112 } 113 114 @Override //批量删除(只删除member表的消息,不删除关联表team的消息) 115 public int batchDeleteById(List<Integer> ids) { 116 SqlSession sqlSession = MyBatisUtils.getSqlSession(); 117 try { 118 return sqlSession.delete("memberNameSpace.batchDeleteById", ids); 119 } catch (Exception e) { 120 sqlSession.rollback(); 121 System.out.println("error:"+e.getMessage()); 122 } finally { 123 sqlSession.commit(); 124 MyBatisUtils.closeSqlSession(); 125 } 126 return 0; 127 } 128 129 }
1 package test.member; 2 3 import java.util.ArrayList; 4 import java.util.HashSet; 5 import java.util.List; 6 import java.util.Set; 7 8 import org.junit.Test; 9 10 import com.shore.o2m.dao.IMemberDao; 11 import com.shore.o2m.dao.ITeamDao; 12 import com.shore.o2m.dao.impl.MemberDao; 13 import com.shore.o2m.dao.impl.TeamDao; 14 import com.shore.o2m.entity.Member; 15 import com.shore.o2m.entity.Team; 16 17 /** 18 * @author DSHORE/2020-3-17 19 * 20 */ 21 public class TestMemberDao { 22 IMemberDao memberDao = new MemberDao(); 23 ITeamDao teamDao = new TeamDao(); 24 25 @Test //新增 26 public void testAdd() { 27 Member member = new Member(); 28 member.setName("王五"); 29 member.setSex(1); 30 31 Member member2 = new Member(); 32 member2.setName("赵六"); 33 member2.setSex(0); 34 35 //1、新建的方式 36 Team team = new Team(); 37 team.setName("峡谷抓河蟹"); 38 team.setDescription("王者荣耀战队名称"); 39 40 Set<Member> members = new HashSet<Member>(); 41 team.setMembers(members); 42 43 //2、使用数据中已有的数据 的方式 44 /*Team team = teamDao.findByTeamId(2); 45 member.setTeam(team);*/ 46 47 member.setTeam(team); 48 member2.setTeam(team); 49 50 System.out.println(teamDao.addTeam(team));//返回值:1 说明插入数据成功 51 System.out.println(memberDao.addMember(member));//返回值:1 52 System.out.println(memberDao.addMember(member2));//返回值:1 53 } 54 55 @Test //更新(修改) 56 public void testUpdate() { 57 Member member = new Member(); 58 member.setId(1); 59 member.setName("张三"); 60 member.setSex(1); 61 62 //把张三的所在战队id是1的,改为战队id是2。 63 Team team = teamDao.findByTeamId(2); 64 member.setTeam(team); 65 66 System.out.println(memberDao.updateMember(member));//返回值:1 67 } 68 69 @Test //根据id查询 70 public void testFindById() { 71 System.out.println(teamDao.findByTeamId(1));//返回值:com.shore.o2m.entity.Team@722d95b3 72 System.out.println(memberDao.findByMemberId(3));//返回值:Member [id=3, name=王五, sex=1, team=com.shore.o2m.entity.Team@6273305c] 73 } 74 75 @Test //多条件查询 76 public void testMulticonditionalQuery() { 77 //返回值:[Member [id=2, name=李四, sex=0, team=com.shore.o2m.entity.Team@5dd2b9b7]] 78 System.out.println(memberDao.multiconditionalQuery("飞虎队", null)); 79 80 //返回值:[Member [id=1, name=张三, sex=1, team=com.shore.o2m.entity.Team@451c0d60]] 81 System.out.println(memberDao.multiconditionalQuery(null, "张三")); 82 83 //返回值:[Member [id=1, name=张三, sex=1, team=com.shore.o2m.entity.Team@5a0029ac]] 84 System.out.println(memberDao.multiconditionalQuery("峡谷抓河蟹", "张三")); 85 } 86 87 @Test //查询指定战队下,所有队员 88 public void testListAllByTeam() { 89 List<Member> members = memberDao.listAllByTeam("峡谷抓河蟹"); 90 if (members == null) { 91 System.out.println("members is null。"); 92 } else { 93 //System.out.println(members.get(0)); 94 for (Member me : members) { 95 System.out.println(me); 96 /*返回值: 97 * Member [id=4, name=赵六, sex=0, team=com.shore.o2m.entity.Team@337b4703] 98 * Member [id=1, name=张三, sex=1, team=com.shore.o2m.entity.Team@6273305c] 99 * Member [id=3, name=王五, sex=1, team=com.shore.o2m.entity.Team@786c1a82] 100 * */ 101 } 102 } 103 } 104 105 @Test //查询所有战队 106 public void testListAll() { 107 List<Team> teams = teamDao.listAll(); 108 if (teams == null) { 109 System.out.println("teams is null。"); 110 } else { 111 //System.out.println(teams.get(0)); 112 for (Team te : teams) { 113 System.out.println(te); 114 /*返回值: 115 * com.shore.o2m.entity.Team@4a57ea52 116 * com.shore.o2m.entity.Team@51d8d39f 117 * */ 118 } 119 } 120 } 121 122 @Test //删除 (只删除member表的消息,不删除关联表team的消息) 123 public void testDelete() { 124 System.out.println(memberDao.deleteMember(7));//返回值:1 说明删除数据成功 125 } 126 127 @Test // 批量删除 (只删除member表的消息,不删除关联表team的消息) 128 public void testBatchDelete() { 129 List<Integer> ids = new ArrayList<Integer>(); 130 ids.add(4); 131 ids.add(5); 132 ids.add(6); 133 System.out.println(memberDao.batchDeleteById(ids));//返回值:3 说明批量删除数据成功 134 } 135 }
到此已完结!有任何问题,可留言。
mybatis单向一对一关联映射:https://www.cnblogs.com/dshore123/p/12489304.html
mybatis单向一对多关联映射:https://www.cnblogs.com/dshore123/p/12493450.html
mybatis单向多对多关联映射:https://www.cnblogs.com/dshore123/p/12526016.html
原创作者:DSHORE 作者主页:http://www.cnblogs.com/dshore123/ 原文出自:https://www.cnblogs.com/dshore123/p/12493450.html 版权声明:欢迎转载,转载务必说明出处。(如果本文对您有帮助,可以点击一下右下角的 推荐,或评论,谢谢!) |