MyBatis中的连接池及事物控制配置过程
目录
- 1.连接池
- 2.mybatis中的事物
- 1.if语句的设置
- 2.mybatis中的多表查询
1.连接池
在实际开发中都会使用连接池
因为它可以减少我们获取连接所消耗的时间
连接池就是用于存储连接的一个容器,容器其实就是一个集合对象,该集合必须是线程安全的,不能两个线程拿到统一连接,该集合还必须实现队列特性:先进先出
Mybatis连接提供了.种方式的怕配置:
- 配置位置:主配置文件SqlMapConfig.xml中的dataSource标签,type属性就是标识采用何种连接池方式
- type属性的取值:POOLED:采用传统的javax.sql.DataSource规范中的连接池,mybatis中有针对规范的实现UNPOOLED:采用传统的获取连接的方式,虽然也实现javax.sql.DataSource接口,但是并没有使用池的思想JNDI:采用服务器提供的JNDI技术,来获取DataSource对象,不同的服务器所能拿到DataSource是不一样的
- 注意:如果不是web或者maven的wai工程是不能使用的,tomcat服务器,采用连接池就是dbcp连接池
2.mybatis中的事物
1.事物
什么是事物
事物的四大特性ACID
不考虑隔离性会产生的3个问题
解决办法:四种隔离级别
它是通过sqlsession对象的commit方法和rollback方法实现事物的提交和回滚
1.if语句的设置
在IUserDao.xml设置
通过判断条件进行查询以及通过多个id进行查询
<!--根据条件查询--> <!--<select id="findUserByCondition" resultType="com.mybatisD.domain.User"> select * from user where 1=1 <if test="username != null"> and username = #{username} </if> <if test="sex != null"> and sex = #{sex} </if> </select>--> <select id="findUserByCondition" resultType="com.mybatisD.domain.User"> select * from user <where> <if test="username != null"> and username = #{username} </if> <if test="sex != null"> and sex = #{sex} </if> </where> </select> <!--根据queryvo中的id集合实现查询用户列表--> <select id="findUserInIds" resultType="com.mybatisD.domain.User" parameterType="com.mybatisD.domain.QueryVo"> select * from user <where> <if test="ids != null and ids.size()>0"> <foreach collection="ids" open="and id in (" close=" )" item="uid" separator=","> #{uid} </foreach> </if> </where> </select>
设置QueryVo实现类
package com.mybatisD.domain; import java.util.List; /** * @author :程序员徐大大 * @description:TODO * @date :2022-01-21 16:05 */ public class QueryVo { private User user; private List<Integer> ids; public User getUser() { return user; } public void setUser(User user) { this.user = user; } public List<Integer> getIds() { return ids; } public void setIds(List<Integer> ids) { this.ids = ids; } }
设置IUserDao实现类
package com.mybatisD.dao; import com.mybatisD.domain.QueryVo; import com.mybatisD.domain.User; import org.apache.ibatis.annotations.Select; import java.util.List; /* * 用户持久层接口 * */ public interface IUserDao { // 查询所有操作 // @Select("select * from user") 这是用注解方法 List<User> findAll(); // 保存方法 void saveUser(User user); //更新用户 void updateUser(User user); //根据ID删除用户 void deleteUser(Integer userId); //根据查询一个用户 User findById(Integer userId); //根据名称模糊查询用户 List<User> findByName(String username); //查询用户总数 int findTotal(); //根据queryVo中的条件查询用户 List<User> findUserByVo(QueryVo vo); //根据条件查询 //查询的条件,有可能有用户名,有可能有性别 有可能有地址,也有可能都没有 List<User> findUserByCondition(User u); /* * 根据queryvo中提供的id集合查询用户信息 * */ List<User> findUserInIds(QueryVo vo); }
测试方法
@Test public void testFindByCondition(){ User u = new User(); u.setUsername("王五"); u.setSex("女"); //执行查询条件 List<User> users = userDao.findUserByCondition(u); for (User user: users) { System.out.println(user); } } //测试使用Query作为查询条件 @Test public void testFindInIds(){ QueryVo vo = new QueryVo(); List<Integer> list = new ArrayList<Integer>(); list.add(2); list.add(5); list.add(10); vo.setIds(list); List<User> users = userDao.findUserInIds(vo); for (User u: users) { System.out.println(u); } }
全部代码在文章最后展出
2.mybatis中的多表查询
表之间的关系:
- 一对多
- 多对一
- 一对一
- 多对多
示例:用户和账户
- 一个用户可以有多个账户
- 一个账户只能属于一个用户(多个账户也可以属于同一个用户)
步骤:
- 先建立两张表、用户表,账户表,让用户表和账户表之间具备一对多的关系,需要使用外键在账户中添加
- 建立两个实体类:用户和账户实体类、让用户和账户实体类能体现出来一对多的关系
- 建立两个配置文件:用户配置文件。账户的配置文件
- 当我们查询用户时,可以同时得到用户下所包含的账户信息
- 当我们查询账户时,可以同时得到账户的所属信息
1.简单实现
表数据
创建Account实现类
package com.mybatisD.domain; import java.io.Serializable; /** * @author :程序员徐大大 * @description:TODO * @date :2022-01-22 16:02 */ public class Account implements Serializable { private Integer id; private Integer uid; private double money; 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 + '}'; } }
再创建与user进行连接的AccountUser实现类、其中toString去调用父类的toString
package com.mybatisD.domain; /** * @author :程序员徐大大 * @description:TODO * @date :2022-01-22 16:25 */ public class AccountUser extends Account{ private String username; private String address; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } @Override public String toString() { return super.toString()+" AccountUser{" + "username='" + username + '\'' + ", address='" + address + '\'' + '}'; } }
设置IAccountDao
package com.mybatisD.dao; import com.mybatisD.domain.Account; import com.mybatisD.domain.AccountUser; import java.util.List; public interface IAccountDao { //查询所有账户 List<Account> findAll(); //查询账户,并且带有用户名称和地址信息 List<AccountUser> findAllAccount(); }
配置IAccountDao.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.mybatisD.dao.IAccountDao"> <select id="findAll" resultType="com.mybatisD.domain.Account" > select * from account </select> <!--查询所有同时包含用户信息--> <select id="findAllAccount" resultType="com.mybatisD.domain.AccountUser"> SELECT a.*,u.username,u.address FROM account a,USER u WHERE u.id = a.uid </select> </mapper>
配置数据库连接SqlMaoConfig.xml文件
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <!--配置properties文件 可以在标签内部配置数据库的信息,也可以通过属性引用外部配置信息 resource属性:用于指定配置文件的位置,是按照类路径的写法来写平且必须存在与类路径下 --> <properties resource="jdbcConfig.properties"> <!--<property name="driver" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/newsql?characterEncoding=utf-8"/> <property name="username" value="root"/> <property name="password" value=""/>--> </properties> <!--配置环境--> <environments default="mysql"> <!--配置mysql环境--> <environment id="mysql"> <!--配置事物类型--> <transactionManager type="JDBC"></transactionManager> <dataSource type="POOLED"> <!--配置连接数据库的4个信息--> <property name="driver" value="${jdbc.driver}"/> <property name="url" value="${jdbc.url}"/> <property name="username" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> </dataSource> </environment> </environments> <!--指定映射配置文件的位置,映射配置文件指的是每个到独立的配置文件--> <mappers> <mapper resource="com/mybatisD/dao/IUserDao.xml"/> <mapper resource="com/mybatisD/dao/IAccountDao.xml"/> </mappers> <!--如果要是用注解来配置的话,此处应该使用class属性指定被注解的dao全限定类名--> <!--<mappers> <mapper class="com.mybatisD.dao.IUserDao"/> </mappers>--> <!--<mappers> <!–package标签用于指定doa接口所在的包,当指定了之后就不需要在写mapper以及resource或者class了–> <package name="com.mybatisD.domain"/> </mappers>--> </configuration>
配置jdbc.properties
jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/newsql?characterEncoding=utf-8 jdbc.username=root jdbc.password=
配置日志文件
log4j.rootCategory=debug,CONSOLE, LOGFILE log4j.logger.org.apache.axis.enterprise=FATAL, CONSOLE log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout log4j.appender.CONSOLE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x -%m\n log4j.appender.LOGFILE=org.apache.log4j.FileAppender log4j.appender.LOGFILE.File=d:\axis.log log4j.appender.LOGFILE.Append=true log4j.appender.LOGFILE.layout=org.apache.log4j.PatternLayout log4j.appender.LOGFILE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x -%m\n
测试类
package com.mybatisJ.test; import com.mybatisD.dao.IAccountDao; import com.mybatisD.dao.IUserDao; import com.mybatisD.domain.Account; import com.mybatisD.domain.AccountUser; import com.mybatisD.domain.QueryVo; import com.mybatisD.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.ArrayList; import java.util.Date; import java.util.List; /** * @author :程序员徐大大 * @description:TODO * @date :2022-01-22 16:07 */ public class AccountTest { private InputStream in; private SqlSession sqlSession; private IAccountDao accountDao; @Before//用于在测试方法执行之前执行 public void init()throws Exception{ in = Resources.getResourceAsStream("SqlMapConfig.xml"); SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder(); SqlSessionFactory factory = builder.build(in); sqlSession = factory.openSession(); //4.使用SqlSession创建Dao接口的代理对象 accountDao = sqlSession.getMapper(IAccountDao.class); } @After//用于在测试方法之后执行 public void destory() throws Exception{ //添加提交事物,不添加无法提交 sqlSession.commit(); sqlSession.close(); in.close(); } @Test public void testFindAll() throws Exception{ List<Account> accounts = accountDao.findAll(); for (Account account: accounts) { System.out.println(account); } } @Test public void findAllAccount(){ List<AccountUser> accountUsers = accountDao.findAllAccount(); for (AccountUser au: accountUsers) { System.out.println(au); } } }
2.以上是没有进行封装,下面就是封装一对一关系的映射
配置封装IAcountDao.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.mybatisD.dao.IAccountDao"> <!--定义封装account的resultMap--> <resultMap id="accountUserMap" type="com.mybatisD.domain.Account"> <id property="id" column="aid"></id> <result property="uid" column="uid"></result> <result property="money" column="money"></result> <!--一对一的关系映射,配置封装user内容--> <association property="user" column="uid" javaType="com.mybatisD.domain.User"> <id property="id" column="id"></id> <result column="username" property="username"></result> <result column="address" property="address"></result> <result column="sex" property="sex"></result> <result column="birthday" property="birthday"></result> </association> </resultMap> <select id="findAll" resultMap="accountUserMap" > select u.*,a.id as aid,a.uid,a.money from account a,user u where u.id = a.uid </select> <!--查询所有同时包含用户信息--> <select id="findAllAccount" resultType="com.mybatisD.domain.AccountUser"> SELECT a.*,u.username,u.address FROM account a,USER u WHERE u.id = a.uid </select> </mapper>
在Account实现类加入User方法
package com.mybatisD.domain; import java.io.Serializable; /** * @author :程序员徐大大 * @description:TODO * @date :2022-01-22 16:02 */ public class Account implements Serializable { private Integer id; private Integer uid; private double money; 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 + '}'; } }
实现IAccountDao的接口
package com.mybatisD.dao; import com.mybatisD.domain.Account; import com.mybatisD.domain.AccountUser; import java.util.List; public interface IAccountDao { //查询所有账户 List<Account> findAll(); //查询账户,并且带有用户名称和地址信息 List<AccountUser> findAllAccount(); }
测试实现
package com.mybatisJ.test; import com.mybatisD.dao.IAccountDao; import com.mybatisD.dao.IUserDao; import com.mybatisD.domain.Account; import com.mybatisD.domain.AccountUser; import com.mybatisD.domain.QueryVo; import com.mybatisD.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.ArrayList; import java.util.Date; import java.util.List; /** * @author :程序员徐大大 * @description:TODO * @date :2022-01-22 16:07 */ public class AccountTest { private InputStream in; private SqlSession sqlSession; private IAccountDao accountDao; @Before//用于在测试方法执行之前执行 public void init()throws Exception{ in = Resources.getResourceAsStream("SqlMapConfig.xml"); SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder(); SqlSessionFactory factory = builder.build(in); sqlSession = factory.openSession(); //4.使用SqlSession创建Dao接口的代理对象 accountDao = sqlSession.getMapper(IAccountDao.class); } @After//用于在测试方法之后执行 public void destory() throws Exception{ //添加提交事物,不添加无法提交 sqlSession.commit(); sqlSession.close(); in.close(); } //查询连接方法其中包括用户的一些信息 @Test public void testFindAll() throws Exception{ List<Account> accounts = accountDao.findAll(); for (Account account: accounts) { System.out.println("-----------------------"); System.out.println(account); System.out.println(account.getUser()); } } //查询account的信息 @Test public void findAllAccount(){ List<AccountUser> accountUsers = accountDao.findAllAccount(); for (AccountUser au: accountUsers) { System.out.println(au); } } }
3.一对多关系映射,主表实体应该包含从表实体的集合引用
但是在User与Account的数据库表中可以发现有的User数据中是没有Account的数据,在下面就是一对多的关系映射
在user实现类进行增加Account类
package com.mybatisD.domain; import java.io.Serializable; import java.util.Date; import java.util.List; public class User implements Serializable { private Integer id; private String username; private Date birthday; private String sex; private String address; private List<Account> account; //一对多关系映射,主表实体应该包含从表实体的集合引用 public List<Account> getAccount() { return account; } public void setAccount(List<Account> account) { this.account = account; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } @Override public String toString() { return "User{" + "id=" + id + ", username='" + username + '\'' + ", birthday=" + birthday + ", sex='" + sex + '\'' + ", address='" + address + '\'' + '}'; } }
在配置IUserDao.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.mybatisD.dao.IUserDao"> <!--定义user的resultMap--> <resultMap id="userAccountMap" type="com.mybatisD.domain.User"> <id property="id" column="id"></id> <id property="username" column="username"></id> <id property="sex" column="sex"></id> <id property="birthday" column="birthday"></id> <!--配置user对象中account集合的映射--> <collection property="account" ofType="com.mybatisD.domain.Account"> <id column="aid" property="id"></id> <id column="uid" property="uid"></id> <id column="money" property="money"></id> </collection> </resultMap> <!--配置查询所有--> <select id="findAll" resultMap="userAccountMap"> select * from user u left outer join account a on u.id = a.uid </select> </mapper>
测试类
package com.mybatisJ.test; import com.mybatisD.dao.IAccountDao; import com.mybatisD.dao.IUserDao; import com.mybatisD.domain.Account; import com.mybatisD.domain.AccountUser; import com.mybatisD.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; /** * @author :程序员徐大大 * @description:TODO * @date :2022-01-22 16:07 */ public class userTest { private InputStream in; private SqlSession sqlSession; private IUserDao userDao; @Before//用于在测试方法执行之前执行 public void init()throws Exception{ in = Resources.getResourceAsStream("SqlMapConfig.xml"); SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder(); SqlSessionFactory factory = builder.build(in); sqlSession = factory.openSession(); //4.使用SqlSession创建Dao接口的代理对象 userDao = sqlSession.getMapper(IUserDao.class); } @After//用于在测试方法之后执行 public void destory() throws Exception{ //添加提交事物,不添加无法提交 sqlSession.commit(); sqlSession.close(); in.close(); } //查询连接方法其中包括用户的一些信息 @Test public void testFindAll() throws Exception{ List<User> users = userDao.findAll(); for (User user: users) { System.out.println(user); System.out.println(user.getAccount()); } } }
结果
4.多对多
示例:用户和角色
- 一个用户可以有多个角色
- 一个角色可以赋予多个用户
步骤:
- 先建立两张表、用户表,角色表,让用户表和角色表具备多对多的关系,需要使用中间表,中间表包含各自主键在中间表中是外键
- 建立两个实体类:用户和角色实体类、让用户和角色实体类能体现出来多对多的关系、各自包含对方一个集合引用
- 建立两个配置文件:用户配置文件。角色的配置文件
- 当我们查询用户时,可以同时得到用户下所包含的角色信息
- 当我们查询角色时,可以同时得到角色的赋予的用户信息
role表
多对多关系表user_role
创建Role实体类
其中主要的是多对多的关系映射User
package com.mybatisD.domain; import java.io.Serializable; import java.util.List; /** * @author :程序员徐大大 * @description:TODO * @date :2022-01-22 20:07 */ public class Role implements Serializable { private Integer roleId; private String roleName; private String roleDesc; //多对多的关系映射,一个角色可以赋予多个用户 private List<User> users; public List<User> getUsers() { return users; } public void setUsers(List<User> users) { this.users = users; } public Integer getRoleId() { return roleId; } public void setRoleId(Integer roleId) { this.roleId = roleId; } public String getRoleName() { return roleName; } public void setRoleName(String roleName) { this.roleName = roleName; } public String getRoleDesc() { return roleDesc; } public void setRoleDesc(String roleDesc) { this.roleDesc = roleDesc; } @Override public String toString() { return "Role{" + "roleId=" + roleId + ", roleName='" + roleName + '\'' + ", roleDesc='" + roleDesc + '\'' + '}'; } }
User实体类的关系映射Role
package com.mybatisD.domain; import java.io.Serializable; import java.util.Date; import java.util.List; public class User implements Serializable { private Integer id; private String username; private Date birthday; private String sex; private String address; //多对多的关系映射,一个用户可以具备多个角色 private List<Role> roles; public List<Role> getRoles() { return roles; } public void setRoles(List<Role> roles) { this.roles = roles; } private List<Account> account; //一对多关系映射,主表实体应该包含从表实体的集合引用 public List<Account> getAccount() { return account; } public void setAccount(List<Account> account) { this.account = account; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } @Override public String toString() { return "User{" + "id=" + id + ", username='" + username + '\'' + ", birthday=" + birthday + ", sex='" + sex + '\'' + ", address='" + address + '\'' + '}'; } }
IROleDao的接口
package com.mybatisD.dao; import com.mybatisD.domain.Role; import java.util.List; public interface IRoleDao { //查询所有角色 List<Role> findAll(); }
IUserDao的接口
package com.mybatisD.dao; import com.mybatisD.domain.QueryVo; import com.mybatisD.domain.User; import org.apache.ibatis.annotations.Select; import java.util.List; /* * 用户持久层接口 * */ public interface IUserDao { // 查询所有操作 // @Select("select * from user") 这是用注解方法 List<User> findAll(); }
配置IRoleDao.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.mybatisD.dao.IRoleDao"> <!--定义role表的ResultMap--> <resultMap id="roleMap" type="com.mybatisD.domain.Role"> <id property="roleId" column="id"></id> <result property="roleName" column="role_name"></result> <result property="roleDesc" column="role_desc"></result> <collection property="users" ofType="com.mybatisD.domain.User"> <id column="id" property="id"></id> <result column="username" property="username"></result> <result column="address" property="address"></result> <result column="sex" property="sex"></result> <result column="birthday" property="birthday"></result> </collection> </resultMap> <select id="findAll" resultMap="roleMap"> select u.*,r.id as rid,r.role_name,r.role_desc from role r left outer join user_role ur on r.id = ur.rid left outer join user u on u.id = ur.uid; </select> </mapper>
配置IUserDao.xml中的多对多Role
<?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.mybatisD.dao.IUserDao"> <!--定义user的resultMap--> <resultMap id="userMap" type="com.mybatisD.domain.User"> <id property="id" column="id"></id> <result property="username" column="username"></result> <result property="address" column="address"></result> <result property="sex" column="sex"></result> <result property="birthday" column="birthday"></result> <collection property="roles" ofType="com.mybatisD.domain.Role"> <id property="roleId" column="rid"></id> <result property="roleName" column="role_name"></result> <result property="roleDesc" column="role_desc"></result> </collection> </resultMap> <!--配置查询所有--> <select id="findAll" resultMap="userMap"> select u.*,r.id as rid,r.role_name,r.role_desc from user u left outer join user_role ur on u.id = ur.rid left outer join role r on r.id = ur.uid; </select> </mapper>
配置SqlMapConfig.xml文件
其中下面的配置包路径名
<mappers > <!--package标签用于指定doa接口所在的包,当指定了之后就不需要在写mapper以及resource或者class了--> <package name="com.mybatisD.dao"/> </mappers>
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <!--配置properties文件 可以在标签内部配置数据库的信息,也可以通过属性引用外部配置信息 resource属性:用于指定配置文件的位置,是按照类路径的写法来写平且必须存在与类路径下 --> <properties resource="jdbcConfig.properties"> <!--<property name="driver" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/newsql?characterEncoding=utf-8"/> <property name="username" value="root"/> <property name="password" value=""/>--> </properties> <!--配置环境--> <environments default="mysql"> <!--配置mysql环境--> <environment id="mysql"> <!--配置事物类型--> <transactionManager type="JDBC"></transactionManager> <dataSource type="POOLED"> <!--配置连接数据库的4个信息--> <property name="driver" value="${jdbc.driver}"/> <property name="url" value="${jdbc.url}"/> <property name="username" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> </dataSource> </environment> </environments> <!--指定映射配置文件的位置,映射配置文件指的是每个到独立的配置文件--> <!--<mappers> <mapper resource="com/mybatisD/dao/IUserDao.xml"/> <mapper resource="com/mybatisD/dao/IAccountDao.xml"/> </mappers>--> <!--如果要是用注解来配置的话,此处应该使用class属性指定被注解的dao全限定类名--> <!--<mappers> <mapper class="com.mybatisD.dao.IUserDao"/> </mappers>--> <mappers > <!--package标签用于指定doa接口所在的包,当指定了之后就不需要在写mapper以及resource或者class了--> <package name="com.mybatisD.dao"/> </mappers> </configuration>
测试role多对多User
package com.mybatisJ.test; import com.mybatisD.dao.IRoleDao; import com.mybatisD.dao.IUserDao; import com.mybatisD.domain.Role; import com.mybatisD.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; /** * @author :程序员徐大大 * @description:TODO * @date :2022-01-22 16:07 */ public class roleTest { private InputStream in; private SqlSession sqlSession; private IRoleDao roleDao; @Before//用于在测试方法执行之前执行 public void init()throws Exception{ in = Resources.getResourceAsStream("SqlMapConfig.xml"); SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder(); SqlSessionFactory factory = builder.build(in); sqlSession = factory.openSession(); //4.使用SqlSession创建Dao接口的代理对象 roleDao = sqlSession.getMapper(IRoleDao.class); } @After//用于在测试方法之后执行 public void destory() throws Exception{ //添加提交事物,不添加无法提交 sqlSession.commit(); sqlSession.close(); in.close(); } //查询角色的一些信息 @Test public void testFindAll() throws Exception { List<Role> roles = roleDao.findAll(); for (Role role: roles) { System.out.println(role); System.out.println(role.getUsers()); } } }
测试User多对多Role
package com.mybatisJ.test; import com.mybatisD.dao.IAccountDao; import com.mybatisD.dao.IUserDao; import com.mybatisD.domain.Account; import com.mybatisD.domain.AccountUser; import com.mybatisD.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; /** * @author :程序员徐大大 * @description:TODO * @date :2022-01-22 16:07 */ public class userTest { private InputStream in; private SqlSession sqlSession; private IUserDao userDao; @Before//用于在测试方法执行之前执行 public void init()throws Exception{ in = Resources.getResourceAsStream("SqlMapConfig.xml"); SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder(); SqlSessionFactory factory = builder.build(in); sqlSession = factory.openSession(); //4.使用SqlSession创建Dao接口的代理对象 userDao = sqlSession.getMapper(IUserDao.class); } @After//用于在测试方法之后执行 public void destory() throws Exception{ //添加提交事物,不添加无法提交 sqlSession.commit(); sqlSession.close(); in.close(); } //查询连接方法其中包括用户的一些信息 @Test public void testFindAll() throws Exception{ List<User> users = userDao.findAll(); for (User user: users) { System.out.println(user); System.out.println(user.getRoles()); } } }
到此这篇关于MyBatis中的连接池以及事物控制的文章就介绍到这了,更多相关MyBatis连接池事物控制内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!