Mybatis总结
花了一个小时列举了常见的Mybatis使用场景1.一对一的场景2. 一对多的场景3.多对多的场景在使用之前,通常在项目中做一些提前准备。a.往项目中导入jar包导入mybatis框架必须要用到的jar包 mybatis-3.3.0.jar和 ojdbc14.jar但根据项目需要,有时会导入其他包,比如log4j-1.2.17.jar这个包可以用来生成日志有时会导入junit-4.7.jar,这个jar包主要为项目提供单元测试。b.在项目的src目录下创建文件mybatis-config.xml文件<? xml version = "1.0" encoding = "utf-8" ?>< configuration >< properties resource = "oracle.properties" ><!-- 注意:是applications.properties文件中的值优先级高 --></ properties >< typeAliases >< typeAlias alias = "Book" type = "com.lm.bean.Book" /></ typeAliases >< environments default = "development" >< environment id = "development" >< transactionManager type = "JDBC" />< dataSource type = "POOLED" ><!-- 当数据库类型为mysql时使用下面的属性<property name="driver" value="com.mysql.jdbc.Driver" /><property name=" url " value="jdbc:mysql:// localhost :3306/test" />-->< property name = "driver" value = "${driver}" />< property name = "url" value = "${url}" />< property name = "username" value = "${username}" />< property name = "password" value = "${password}" /></ dataSource ></ environment ></ environments >< mappers >< mapper resource = "com/lm/mapper/BookMapper.xml" /></ mappers ></ configuration >
如果项目中导入了 log4j-1.2.17.jar包,会在src目录下配置相关的log4j.properties文件log4j.properties文件的内容log4j.rootLogger= DEBUG, stdoutlog4j.appender.stdout = org.apache.log4j.ConsoleAppenderlog4j.appender.stdout.layout= org.apache.log4j.PatternLayoutlog4j.appender.stdout.layout.ConversionPattern= %d [%-5p] %c - %m%n#show sqllog4j.logger.java.sql.ResultSet= INFOlog4j.logger.java.sql.Connection= DEBUGlog4j.logger.java.sql.Statement= DEBUGlog4j.logger.java.sql.PreparedStatement= DEBUG有时候连接数据库的时候也会创建oracle.properties文件,这是为了项目以后更换了数据库之后(如oracle更换成mysql数据库)不用修改 mybatis-config.xml文件。oracle.properties文件的内容driver=oracle.jdbc.driver.OracleDriverurl=jdbc:oracle:thin:@localhost:1521:XEusername=oraclepassword=oraclemysql.properties文件的内容driver=com.mysql.jdbc.Driverurl=jdbc:mysql://localhost:3306/testusername=oraclepassword=oracle
所有准备工作做完之后开始逐一解决需求1.一对一场景(丈夫对妻子)首先写pojo类
class Wife implements Serializable{public class Wife implements Serializable{/****/private static final long serialVersionUID = 1L; //实现序列化接口是为了有时进行二次缓存会用到private Integer wifeId ;//这里使用Integer是为了避免int类型默认值为0的情况private String name ;private Integer age ;set/gettoString
}丈夫类
public class Husband implements Serializable{/****/private static final long serialVersionUID = 1L;private Integer husbandId ;private String name ;private Integer age ;private Wife wife ;set/gettoString}然后创建数据库create table wifes(wife_id number primary key,name varchar2(15) not null,age number);create table husbands(husband_id number primary key,name varchar2(15) not null,age number,wife_id number references wifes(wife_id));先往数据库中插入几条数据方便测试insert into wifes values (1, 'xiaowen' ,25);insert into wifes values (2, 'xiaodie' ,25);insert into wifes values (3, 'xiaozhang' ,25);insert into husbands values (1, 'xiaomeng' ,23,1);insert into husbands values (2, 'xiaoli' ,23,3);insert into husbands values (3, 'xiaoyi' ,23,2);
接着写映射接口public interface OtoMapper{public Husband findHusbandWithWifeById(int id);//通过id查询带有妻子信息的丈夫public void insertHusband(Husband husband);}配置与接口相对应的配置文件<!-- 注意namespace的名字一定要和接口的全名完全对应 --><mapper namespace="OtoMapper"><!-- 注意类型一定要时所对应的类的全名 --><resultMap id="WifeResult" type="Wife"><id property="wifeId" column="wife_id" /><result property="name" column="name" /><result property="age" column="age" /></resultMap><resultMap id="HusbandResult" type="Husband"><id property="husbandId" column="husband_id" /><result property="name" column="name" /><result property="age" column="age" /><association property="wife" resultMap=" WifeResult " /></resultMap>
< insert id = "insertWife" parameterType = "Wife" >< selectKey keyProperty = "wifeId" resultType = "int" order = "BEFORE" >select my_seq.nextval from dual</ selectKey >insert into wifesvalues(#{wifeId},#{name},#{age})</ insert >< insert id = "insertHusband" parameterType = "Husband" >< selectKey keyProperty = "husbandId" resultType = "int" order = "BEFORE" >select my_seq.nextval from dual</ selectKey ><!--注意插入丈夫的时候一定要妻子对象一定把妻子的id属性写出来-->insert into husbandsvalues(#{husbandId},#{name},#{age},#{wife.wifeId})</ insert ><!-- 注意id一定要和接口中对应的方法名一致 --><select id=" findHusbandWithWifeById " parameterType="int " resultMap=" WifeResult ">select * from husbands where husband_id=#{husbandId}</select><mapper>
然后写测试类,可以使用单元测试,也可以使用main()方法
2.一对多场景(小组对用户)第一步 写pojo类
public class User implements Serializable{/****/private static final long serialVersionUID = 1L;private Integer userId ;private String userName ;private Group group ; //这里维护group对象,是为了将来通过查询user可以显示出在哪个小组中set/gettoString}小组类public class Group implements Serializable{/****/private static final long serialVersionUID = 1L;private Integer groupId ;private String groupName ;private List<User> users ; //查询用户同时显示用户的信息,通常都是在少的一方list多的一方set/gettoString}
2.建数据库表
create table t_group(group_id number primary key,groupName varchar2(15) not null);create table t_user(t_user_id number primary key,userName varchar2(15),group_id number references t_group(group_id) //一对多的时候通常都是多的一方维护少的一方);
先往数据库中插入几条数据方便测试insert into t_group values (1, 'Lol' );insert into t_group values (2, 'JueDi' );insert into t_user values (1, 'zhangsan' ,1);insert into t_user values (2, 'lucy' ,2);insert into t_user values (3, 'tom' ,1);insert into t_user values (4, 'xiaohua' ,2);insert into t_user values (5, 'xiaowen' ,1);
3.写映射接口public interface OtmMapper{public Group findGroupById(int id);public User findUserById(int id);}4.写和接口相关的配置文件<mapper namespace=" OtmMapper "><resultMap id="UserResult" type="User"><id property="userId" column="t_user_id" /><result property="userName" column="userName"></resultMap>
<resultMap id="GroupResult" type="Group"><id property="groupId" column="group_id" /><result proeprty="groupName" column="groupName" /><!--下面的collection可以理解为多个对象组成的集合,正好和pojo类中的list集合对应。这样就能记住--><collection pproperty="users" resultMap=" UserResult "></resultMap><!--以上的配置文件就可以完成查询所需小组,并且小组中包含多个用户信息--><select id=" findGroupById " parameter="int" resultMap=" GroupResult ">select * fromt_group g,t_user uwhere u.group_id=g.group_idand g.group_id=#{groupId}</select><!--注意查询用户的时候,因为用户拥护了小组,也就是说users数据库表中的group外键也要房放进去 以 group.groupId的形式交给Mybatis处理后放入数据库中的user表中形成外键-->< insert id = "insertUser" parameterType = "User" >< selectKey keyProperty = "userId" resultType = "int" order = "BEFORE" >select my_seq.nextval from dual</ selectKey >insert into t_uservalues(#{userId},#{userName},#{group.groupId})</ insert ><!--高能,如果想查询带有小组的信息的用户时,需要下面的配置文件--><resultMap id="UserResltandGroupResult" parameterType="int" extends=" UserResult " ><association property="group" resulMap=" GroupResult " /></resultMap>
<select id=" findUserWithGroupById " parameterType="int" resultMap=" UserResltandGroupResult ">select * from t_user where t_user_id=#{userId}</select>
</mapper>
3.多对多场景(学生对课程)
< resultMap id="帅哥们Result" type="帅哥类"><id property="帅哥id" cloumn="帅哥id"><result property="gender" cloumn="gender"></resultMap><resultMap id="美女们Result" type="美女类"><id property="美女id" cloumn="美女id"><result property="gender" cloumn="gender"></resultMap>// 通过帅哥找美女是这样写的<resultMap id="帅哥们和美女们Result" type="帅哥类" extends="帅哥们Result"> //背会第一句<id property="帅哥id" cloumn="帅哥id"><result property="gender" cloumn="gender"><collection property="美女们" resultMap="美女们Result"> //背会</resultMap>select * from 帅哥和美女们, 帅哥们,美女们where 帅哥id=#{帅哥id}and 帅哥们id=sc.student_idand 美女们id=sc.course_id
MyBatis使用小结
最新推荐文章于 2023-08-23 19:08:20 发布