Mybatis基于配置的crud

在这里插入图片描述

Emp
在这里插入图片描述

public class Emp {
	private Integer id;
	private String name;
	private Integer age;
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Integer getAge() {
		return age;
	}
	public void setAge(Integer age) {
		this.age = age;
	}
}

MybatisUtil

public class MyBatisUtil {
	private static SqlSessionFactory sFactory;
	
	static {
//		加载配置文件
		SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
		try {
			sFactory = builder.build(Resources.getResourceAsReader("SqlMapConfig.xml"));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
//	创建连接
	public static SqlSession getSession() {
		return sFactory.openSession();
	}
	
//	测试连接
	public static void main(String[] args) {
		SqlSession session = MyBatisUtil.getSession();
		System.out.println(session);
		session.close();
	}
}

EmpDao

public class EmpDao {
//	查询所有
	public List<Emp> findAll(){
		SqlSession session = MyBatisUtil.getSession();
//		标识statement用命名空间加sqlId session.selectList(statement)
		List<Emp> list = session.selectList("com.aimuti.dao.EmpDao.findAll");
		session.close();
		return list;
	}
	
//	根据Id查询
	public Emp findById(int id) {
		SqlSession session = MyBatisUtil.getSession();
		Emp emp = session.selectOne("com.aimuti.dao.EmpDao.findById",id);
		session.close();
		return emp;
	}
	
//	添加员工
	public void insert(Emp emp) {
		SqlSession session = MyBatisUtil.getSession();
		try {
			session.insert("com.aimuti.dao.EmpDao.insert",emp);
//			从session中提交事务
			session.commit();
		}catch (Exception e) {
			e.printStackTrace();
//			出现异常就事务回滚
			session.rollback();
		}finally {
			session.close();
		}
	}
	
//	修改员工信息
	public void update(Emp emp) {
		SqlSession session = MyBatisUtil.getSession();
		try {
			session.update("com.aimuti.dao.EmpDao.update", emp);
			session.commit();
		} catch (Exception e) {
			e.printStackTrace();
			session.rollback();
		}finally {
			session.close();
		}
	}

//	根据id删除员工
	public void delete(int id) {
		SqlSession session = MyBatisUtil.getSession();
		try {
			session.delete("com.aimuti.dao.EmpDao.delete",id);
			session.commit();
		} catch (Exception e) {
			e.printStackTrace();
			session.rollback();
		}finally {
			session.close();
		}
	}
}

EmpDao.xml

<?xml version="1.0" encoding="UTF-8" ?>  
<!DOCTYPE mapper PUBLIC "-//ibatis.apache.org//DTD Mapper 3.0//EN"      
 "http://ibatis.apache.org/dtd/ibatis-3-mapper.dtd">
 
<!-- 命名空间需要和Dao的命名一致 -->
<mapper namespace="com.aimuti.dao.EmpDao">
	<!-- resultType:返回的结果类型 -->
	<select id="findAll" resultType="com.aimuti.entity.Emp">
		select * from emp 
	</select>
	
	<!-- 根据Id查找 -->
	<select id="findById" parameterType="integer" resultType="com.aimuti.entity.Emp">
		select * from emp where id = #{id}
	</select>
	
	<!-- 添加 -->
	<insert id="insert" parameterType="com.aimuti.entity.Emp">
		insert into emp(id,name,age) values(#{id},#{name},#{age})
	</insert>
	
	<!-- 修改员工信息 -->
	<update id="update" parameterType="com.aimuti.entity.Emp">
		update emp set name=#{name},age=#{age} where id=#{id}
	</update>
	
	<!-- 删除员工信息 -->
	<delete id="delete" parameterType="integer">
		delete from emp where id=#{id}
	</delete>
</mapper>

	<!-- 在mybatis中#与$的区别 -->
	<!--动态sql是mybatis的主要特性之一,在mapper中定义的参数传到xml中之后,在查询之前mybatis会对其进行动态解析,mybatis为我们提供了两种动态sql的语法:#{} ${},在下面的语句中,如果 username 的值为 zhangsan,则两种方式无任何区别: 
select * from user where name = #{name};
select * from user where name = ${name};
  其解析之后的结果均为
select * from user where name = 'zhangsan';
但是#{}和${}在预编译中处理是不一样的.#{}在预处理是,会把参数部分用一个占位符?代替,
select * from user where name = ?;
而${}则只是简单的字符串转换,在动态解析阶段,该sql语句会被解析成为
select * from user where name = 'zhangsan';
以上,#{} 的参数替换是发生在 DBMS 中,而 ${} 则发生在动态解析过程中。
  那么,在使用过程中我们应该使用哪种方式呢?
  答案是,优先使用 #{}。因为 ${} 会导致 sql 注入的问题。看下面的例子:
select * from ${tableName} where name = #{name}
  在这个例子中,如果表名为
   user; delete user; -- 
  则动态解析之后 sql 如下:
select * from user; delete user; -- where name = ?;
  --之后的语句被注释掉,而原本查询用户的语句变成了查询所有用户信息+删除用户表的语句,会对数据库造成重大损伤,极大可能导致服务器宕机。
但是表名用参数传递进来的时候,只能使用 ${} ,具体原因可以自己做个猜测,去验证。这也提醒我们在这种用法中要小心sql注入的问题。-->

SqlMapConfig.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//ibatis.apache.org//DTD Config 3.0//EN" 
	"http://ibatis.apache.org/dtd/ibatis-3-config.dtd">
	<configuration>
		<environments default="environment">
			<environment id="environment">
				<transactionManager type="JDBC"/>
				<dataSource type="POOLED">
					<property name="url"
					value="jdbc:mysql:///emp?useUnicode=true&amp;characterEncoding=utf8" />
					<property name="driver" value="com.mysql.jdbc.Driver" />
					<property name="username" value="root" />
					<property name="password" value="123456" />
				</dataSource>
			</environment>
		</environments>
		
		<!-- 引入mapper文件  可以有多个mapper -->
		<mappers>
			<mapper resource="EmpDao.xml"/>
			<mapper resource="EmpMapper.xml"/>
			<mapper resource="DeptMapper.xml"/>
		</mappers>
	</configuration>

TestCase

public class TestCase {
	@Test
	//查询所有
	public void test1() {
		EmpDao dao = new EmpDao();
		List<Emp> list = dao.findAll();
		for (Emp emp : list) {
			System.out.println(emp.getName());
		}
	}
	
	@Test
	//根据Id查找
	public void test2() {
		EmpDao dao = new EmpDao();
		Emp emp = dao.findById(2);
		System.out.println(emp.getName());
	}
	
	@Test
	//添加员工
	public void test3() {
		EmpDao dao = new EmpDao();
		Emp emp = new Emp();
		emp.setId(3);
		emp.setName("shm");
		emp.setAge(18);
		dao.insert(emp);
	}
	
	@Test
	//修改员工信息
	public void test4() {
		EmpDao dao = new EmpDao();
		Emp emp = dao.findById(3);
		emp.setName("ncx");
		emp.setAge(18);
		dao.update(emp);
		System.out.println("ojbk");
	}
	
	@Test
	//删除员工
	public void test5() {
		EmpDao dao = new EmpDao();
		dao.delete(3);
		System.out.println("ojbk");
	}

查询结果不贴了,可以自己试一试

使用Mapper映射器
EmpMapper

/**
 *使用Mapper映射器
 *1 Mapper接口名称和对应的映射文件的namespace必须一致
 *2 Mapper接口中的方法名必须和映射文件中对应的SQL元素的ID对应一致
 */
public interface EmpMapper {
	List<Emp> findAll();
	Emp findById(int id);
	void insert(Emp emp);
	void update(Emp emp);
	void delete(int id);
}

EmpMapper.xml

<!-- 命名空间需要和Dao的命名一致 -->
<mapper namespace="com.aimuti.dao.EmpMapper">
	<!-- resultType:返回的结果类型 -->
	<select id="findAll" resultType="com.aimuti.entity.Emp">
		select * from emp 
	</select>
	
	<!-- 根据Id查找 -->
	<!-- 在mybatis中#与$的区别 -->
	<select id="findById" parameterType="integer" resultType="com.aimuti.entity.Emp">
		select * from emp where id = #{id}
	</select>
	
	<!-- 添加 -->
	<insert id="insert" parameterType="com.aimuti.entity.Emp">
		insert into emp(id,name,age) values(#{id},#{name},#{age})
	</insert>
	
	<!-- 修改员工信息 -->
	<update id="update" parameterType="com.aimuti.entity.Emp">
		update emp set name=#{name},age=#{age} where id=#{id}
	</update>
	
	<!-- 删除员工信息 -->
	<delete id="delete" parameterType="integer">
		delete from emp where id=#{id}
	</delete>
</mapper>

TestCase

//	使用mapped映射器
	@Test
	public void test6() {
		SqlSession session = MyBatisUtil.getSession();
		EmpMapper mapper = session.getMapper(EmpMapper.class);
		List<Emp> list = mapper.findAll();
		for (Emp emp : list) {
			System.out.println(emp.getName());
		}
	}

Dept
(处理类中属性和数据库中字段不一致的情况)
在这里插入图片描述

public class Dept{
private Integer id;
	private String name;
	private String loc;
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getLoc() {
		return loc;
	}
	public void setLoc(String loc) {
		this.loc = loc;
	}
}

DeptMapper

public interface DeptMapper {
	List<Dept> findAll();
}

DeptMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>  
<!DOCTYPE mapper PUBLIC "-//ibatis.apache.org//DTD Mapper 3.0//EN"      
 "http://ibatis.apache.org/dtd/ibatis-3-mapper.dtd">
 
	<!-- 命名空间需要和Dao的命名一致 -->
	<mapper namespace="com.aimuti.dao.DeptMapper">
		<!-- resultMap映射结果集,用来处理数据库字段和实体类属性不一致的情况 -->
		<select id="findAll" resultMap="deptMap">
			select * from dept
		</select>
		<!-- type:指的是要处理的实体类,id属性要与上面查询结果resultMap一致 -->
		<!-- property属性是指实体类的属性,column属性实质数据库字段的名称 -->
		<resultMap type="com.aimuti.entity.Dept" id="deptMap">
			<result property="id" column="deptno" />
			<result property="name" column="dname"/>
			<result property="loc" column="loc" />
		</resultMap>
	</mapper>

TestCase

//	实体类属性与数据库字段名不一致的映射
	@Test
	public void test7() {
		SqlSession session = MyBatisUtil.getSession();
		DeptMapper mapper = session.getMapper(DeptMapper.class);
		List<Dept> list = mapper.findAll();
		for (Dept dept : list) {
			System.out.println(dept.getId()+" "+dept.getName());
		}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值