基于代理dao
1.SqlMapConfig.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属性:
用于指定配置文件的位置,是按照类路径的写法来写,并且必须存在于类路径下
url属性:
要求按照url的写法来写地址
URL:Uniform Resource Locator 统一资源定位符y.它是可以唯一标识一个资源的位置
写法:
http://localhost:8080/mybatisserver/demo1Servlet
协议 主机 端口 URI
URI:Uniform Resource Identifier 统一资源标识符。它是在应用中可以唯一定位一个资源的
-->
<properties url="file:///E:/Study/ssm/MybatisCRUD/src/main/resources/jdbcConfig.properties">
<!--<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=utf8"/>
<property name="username" value="root"/>
<property name="password" value="123"/>-->
</properties>
<!--使用typeAliases配置别名,它只能配置domain中类的别名-->
<typeAliases>
<!--typeAliases用于配置别名。type属性指定的是实体类全限定类名。alias属性指定别名
当指定了别名就不再区分大小写
-->
<!--<typeAlias type="com.domain.User" alias="user"></typeAlias>-->
<!--用于指定要配置别名的包。当指定之后。该包下的实体类都会注册别名。并且类名就是别名,不再区分大小写-->
<package name="com.domain"></package>
</typeAliases>
<!--配置环境-->
<environments default="mysql">
<!--配置Mysql环境-->
<environment id="mysql">
<!--配置事务-->
<transactionManager type="JDBC"></transactionManager>
<!--配置连接池-->
<dataSource type="POOLED">
<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/dao/IUserDao.xml"/>-->
<!--package标签是用于指定dao接口所在的包,当指定了之后就不需要在写mapper以及resource
或者class了
-->
<package name="com.dao"></package>
</mappers>
</configuration>
2.jdbcConfig.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=utf8
jdbc.username=root
jdbc.password=123
3.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.dao.IUserDao">
<!--配置查询结果的列名和实体类的属性名的对应关系-->
<resultMap id="userMap" type="com.domain.User">
<!--主键字段的对应-->
<id property="userId" column="id"></id>
<!--非主键字段的对应-->
<result property="userName" column="username"></result>
<result property="userAddress" column="address"></result>
<result property="userSex" column="sex"></result>
<result property="userBirthday" column="birthday"></result>
</resultMap>
<!--查询所有-->
<select id="findAll" resultMap="userMap">
<!--select id userId,username userName,address userAddress,sex userSex,birthday userBirthday from user;-->
select * from user;
</select>
<!--保存用户-->
<insert id="saveUser" parameterType="com.domain.User">
<!--配置插入操作后,获取插入数据的id-->
<selectKey keyProperty="userId" keyColumn="id" resultType="int" order="AFTER">
select last_insert_id();
</selectKey>
insert into user(username,address,sex,birthday)values(#{userName},#{userAddress},#{userSex},#{userBirthday});
</insert>
<!--更新用户-->
<update id="updateUser" parameterType="com.domain.User">
UPDATE user set username=#{username},address=#{address},sex=#{sex},birthday=#{birthday} where id=#{id};
</update>
<!--删除用户-->
<delete id="deleteUser" parameterType="java.lang.Integer">
DELETE from user WHERE id=#{id};
</delete>
<!--根据id查询用户-->
<select id="findById" parameterType="java.lang.Integer" resultType="com.domain.User">
select * from user where id=#{id};
</select>
<!--根据名字模糊查询用户-->
<select id="findByName" parameterType="java.lang.String" resultType="com.domain.User">
<!-- select * from user where username like #{name}; -->
select * from user where username like '%${value}%'
</select>
<!--查询总用户数-->
<select id="findTotal" resultType="java.lang.Integer">
select count(*) from user;
</select>
<!--配置queryVo的条件查询用户-->
<select id="findUserByVo" parameterType="com.domain.QueryVo" resultType="com.domain.User">
select * from user where username like #{user.username};
</select>
</mapper>
4.IUser.dao
package com.dao;
import com.domain.QueryVo;
import com.domain.User;
import java.util.List;
//用户的持久层接口
public interface IUserDao {
//查询所有用户
List<User> findAll();
//保存用户
void saveUser(User user);
//更新操作
void updateUser(User user);
//删除用户
void deleteUser(Integer id);
//根据id查询用户
User findById(Integer id);
//根据名称模糊查询
List<User> findByName(String name);
//查询总的用户数
int findTotal();
//根据queryVo中的条件查询用户
User findUserByVo(QueryVo qureyVo);
}
4.User.java
package com.domain;
import java.io.Serializable;
import java.util.Date;
public class User implements Serializable{
private Integer userId;
private String userName;
private String userAddress;
private String userSex;
private Date userBirthday;
public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserAddress() {
return userAddress;
}
public void setUserAddress(String userAddress) {
this.userAddress = userAddress;
}
public String getUserSex() {
return userSex;
}
public void setUserSex(String userSex) {
this.userSex = userSex;
}
public Date getUserBirthday() {
return userBirthday;
}
public void setUserBirthday(Date userBirthday) {
this.userBirthday = userBirthday;
}
@Override
public String toString() {
return "User{" +
"userId=" + userId +
", userName='" + userName + '\'' +
", userAddress='" + userAddress + '\'' +
", userSex='" + userSex + '\'' +
", userBirthday=" + userBirthday +
'}';
}
}
5.QueryVo.java
package com.domain;
public class QueryVo {
private User user;
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
}
6.MybatisTest.java
package com.test;
import com.dao.IUserDao;
import com.domain.QueryVo;
import com.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.Date;
import java.util.List;
public class MyBatisTest {
private InputStream in;
private SqlSession sqlSession;
private IUserDao userDao;
@Before //用于在测试方法执行之前执行
public void init() throws Exception{
//1.读取配置文件,生成字节输入流
in = Resources.getResourceAsStream("SqlMapConfig.xml");
//2.获取SQLSessionFactory对象
SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
SqlSessionFactory factory = builder.build(in);
//3.获取SqlSession对象
sqlSession = factory.openSession();
//4.获取dao的代理对象
userDao = sqlSession.getMapper(IUserDao.class);
}
@After //用于在测试方法执行之后执行
public void destory() throws Exception{
//提交事务
sqlSession.commit();
//关闭资源
sqlSession.close();
in.close();
}
@Test
public void testFindAll() throws Exception{
//5.执行查询所有方法
List<User> users = userDao.findAll();
for(User user : users){
System.out.println(user);
}
}
//测试保存操作
@Test
public void testSave() throws Exception{
User user = new User();
user.setUserName("modify User");
user.setUserAddress("重庆市永川区");
user.setUserSex("男");
user.setUserBirthday(new Date());
System.out.println("保存前:"+user);
//5.执行保存方法
userDao.saveUser(user);
System.out.println("保存后:"+user);
}
//测试更新操作
@Test
public void testUpdate() throws Exception{
User user = new User();
user.setUserId(51);
user.setUserName("LEE");
user.setUserAddress("北京市朝阳区");
user.setUserSex("女");
user.setUserBirthday(new Date());
//5.执行更新方法
userDao.updateUser(user);
}
//测试删除操作
@Test
public void testDelete() throws Exception{
//5.执行删除方法
userDao.deleteUser(52);
}
//测试根据id查询用户
@Test
public void testFindById() throws Exception{
//5.执行根据id查用户方法
User user = userDao.findById(48);
System.out.println(user);
}
//测试根据名字模糊查询用户
@Test
public void testFindByName() throws Exception{
//5.执行根据名字模糊查询用户方法
//List<User> users = userDao.findByName("%王%");
List<User> users = userDao.findByName("王");
for(User user : users){
System.out.println(user);
}
}
//测试查询总的用户数
@Test
public void testFindTotal() throws Exception{
//5.执行查询总的用户数的方法
int total = userDao.findTotal();
System.out.println(total);
}
//根据queryVo中的条件查询用户
@Test
public void testFindUserByVo() throws Exception{
User user = new User();
user.setUserName("modify User");
user.setUserAddress("重庆市永川区");
user.setUserSex("男");
user.setUserBirthday(new Date());
QueryVo queryVo = new QueryVo();
queryVo.setUser(user);
//5.执行查询总的用户数的方法
User user1 = userDao.findUserByVo(queryVo);
System.out.println(user1);
}
}
传统Dao层开发
1.SqlMapConfig.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>
<!--配置环境-->
<environments default="mysql">
<!--配置Mysql环境-->
<environment id="mysql">
<!--配置事务-->
<transactionManager type="JDBC"></transactionManager>
<!--配置连接池-->
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=utf8"/>
<property name="username" value="root"/>
<property name="password" value="123"/>
</dataSource>
</environment>
</environments>
<!--配置映射文件的位置-->
<mappers>
<mapper resource="com/dao/IUserDao.xml"/>
</mappers>
</configuration>
2.IUser.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.dao.IUserDao">
<!--查询所有-->
<select id="findAll" resultType="com.domain.User">
<!--select id userId,username userName,address userAddress,sex userSex,birthday userBirthday from user;-->
select * from user;
</select>
<!--保存用户-->
<insert id="saveUser" parameterType="com.domain.User">
<!--配置插入操作后,获取插入数据的id-->
<selectKey keyProperty="id" keyColumn="id" resultType="int" order="AFTER">
select last_insert_id();
</selectKey>
insert into user(username,address,sex,birthday)values(#{username},#{address},#{sex},#{birthday});
</insert>
<!--更新用户-->
<update id="updateUser" parameterType="com.domain.User">
UPDATE user set username=#{username},address=#{address},sex=#{sex},birthday=#{birthday} where id=#{id};
</update>
<!--删除用户-->
<delete id="deleteUser" parameterType="java.lang.Integer">
DELETE from user WHERE id=#{id};
</delete>
<!--根据id查询用户-->
<select id="findById" parameterType="java.lang.Integer" resultType="com.domain.User">
select * from user where id=#{id};
</select>
<!--根据名字模糊查询用户-->
<select id="findByName" parameterType="java.lang.String" resultType="com.domain.User">
<!-- select * from user where username like #{name}; -->
select * from user where username like '%${value}%'
</select>
<!--查询总用户数-->
<select id="findTotal" resultType="java.lang.Integer">
select count(*) from user;
</select>
</mapper>
3.IUserDao.java
package com.dao;
import com.domain.User;
import java.util.List;
//用户的持久层接口
public interface IUserDao {
//查询所有用户
List<User> findAll();
//保存用户
void saveUser(User user);
//更新操作
void updateUser(User user);
//删除用户
void deleteUser(Integer id);
//根据id查询用户
User findById(Integer id);
//根据名称模糊查询
List<User> findByName(String name);
//查询总的用户数
int findTotal();
}
4.UserDaoImpl.java
package com.test;
import com.dao.IUserDao;
import com.dao.impl.UserDaoImpl;
import com.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.Date;
import java.util.List;
public class MyBatisTest {
private InputStream in;
private SqlSession sqlSession;
private IUserDao userDao;
@Before //用于在测试方法执行之前执行
public void init() throws Exception{
//1.读取配置文件,生成字节输入流
in = Resources.getResourceAsStream("SqlMapConfig.xml");
//2.获取SQLSessionFactory对象
SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
SqlSessionFactory factory = builder.build(in);
//3.使用工厂对象,创建dao对象
userDao = new UserDaoImpl(factory);
}
@After //用于在测试方法执行之后执行
public void destory() throws Exception{
in.close();
}
@Test
public void testFindAll() throws Exception{
//5.执行查询所有方法
List<User> users = userDao.findAll();
for(User user : users){
System.out.println(user);
}
}
//测试保存操作
@Test
public void testSave() throws Exception{
User user = new User();
user.setUsername("modify User");
user.setAddress("重庆市永川区");
user.setSex("男");
user.setBirthday(new Date());
System.out.println("保存前:"+user);
//5.执行保存方法
userDao.saveUser(user);
System.out.println("保存后:"+user);
}
//测试更新操作
@Test
public void testUpdate() throws Exception{
User user = new User();
user.setId(54);
user.setUsername("LEE");
user.setAddress("北京市朝阳区");
user.setSex("女");
user.setBirthday(new Date());
//5.执行更新方法
userDao.updateUser(user);
}
//测试删除操作
@Test
public void testDelete() throws Exception{
//5.执行删除方法
userDao.deleteUser(57);
}
//测试根据id查询用户
@Test
public void testFindById() throws Exception{
//5.执行根据id查用户方法
User user = userDao.findById(48);
System.out.println(user);
}
//测试根据名字模糊查询用户
@Test
public void testFindByName() throws Exception{
//5.执行根据名字模糊查询用户方法
//List<User> users = userDao.findByName("%王%");
List<User> users = userDao.findByName("王");
for(User user : users){
System.out.println(user);
}
}
//测试查询总的用户数
@Test
public void testFindTotal() throws Exception{
//5.执行查询总的用户数的方法
int total = userDao.findTotal();
System.out.println(total);
}
}
5.User.java
package com.domain;
import java.io.Serializable;
import java.util.Date;
public class User implements Serializable{
private Integer id;
private String username;
private String address;
private String sex;
private Date birthday;
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 String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", address='" + address + '\'' +
", sex='" + sex + '\'' +
", birthday=" + birthday +
'}';
}
}
6.MybatisTest.java
package com.test;
import com.dao.IUserDao;
import com.dao.impl.UserDaoImpl;
import com.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.Date;
import java.util.List;
public class MyBatisTest {
private InputStream in;
private SqlSession sqlSession;
private IUserDao userDao;
@Before //用于在测试方法执行之前执行
public void init() throws Exception{
//1.读取配置文件,生成字节输入流
in = Resources.getResourceAsStream("SqlMapConfig.xml");
//2.获取SQLSessionFactory对象
SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
SqlSessionFactory factory = builder.build(in);
//3.使用工厂对象,创建dao对象
userDao = new UserDaoImpl(factory);
}
@After //用于在测试方法执行之后执行
public void destory() throws Exception{
in.close();
}
@Test
public void testFindAll() throws Exception{
//5.执行查询所有方法
List<User> users = userDao.findAll();
for(User user : users){
System.out.println(user);
}
}
//测试保存操作
@Test
public void testSave() throws Exception{
User user = new User();
user.setUsername("modify User");
user.setAddress("重庆市永川区");
user.setSex("男");
user.setBirthday(new Date());
System.out.println("保存前:"+user);
//5.执行保存方法
userDao.saveUser(user);
System.out.println("保存后:"+user);
}
//测试更新操作
@Test
public void testUpdate() throws Exception{
User user = new User();
user.setId(54);
user.setUsername("LEE");
user.setAddress("北京市朝阳区");
user.setSex("女");
user.setBirthday(new Date());
//5.执行更新方法
userDao.updateUser(user);
}
//测试删除操作
@Test
public void testDelete() throws Exception{
//5.执行删除方法
userDao.deleteUser(57);
}
//测试根据id查询用户
@Test
public void testFindById() throws Exception{
//5.执行根据id查用户方法
User user = userDao.findById(48);
System.out.println(user);
}
//测试根据名字模糊查询用户
@Test
public void testFindByName() throws Exception{
//5.执行根据名字模糊查询用户方法
//List<User> users = userDao.findByName("%王%");
List<User> users = userDao.findByName("王");
for(User user : users){
System.out.println(user);
}
}
//测试查询总的用户数
@Test
public void testFindTotal() throws Exception{
//5.执行查询总的用户数的方法
int total = userDao.findTotal();
System.out.println(total);
}
}