MyBatis实现增删改查与模糊查询

单表增删改查与模糊查询

首先新建lib文件夹导入JBCD和MyBatis的jar包

config文件夹

jdbc.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql:///bd1906?characterEncoding=utf8&useSSL=true
jdbc.username=root
jdbc.password=root

mybatis-config.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!--  mybatis约束文档 -->
<!DOCTYPE configuration
  PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
 <!-- 运行环境 -->
 <properties resource ="jdbc.properties"/>
<typeAliases>
	<package name ="pojo"/>
</typeAliases>
  <environments default="development">
    <environment id="development">
      <!-- 事务默认提交方式 手动提交 -->
      <transactionManager type="JDBC"/>
      <!-- 数据源 -->
      <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/mapper/DeptMapper.xml"/> -->
	<package name = "mapper"/>
  </mappers>
</configuration>

pojo包(类包)

package pojo;

import java.util.List;

/**
 * 部门类
 */
public class Dept {
	private Integer deptno;
	private String dname;
	private String loc;
	public Dept() {
		super();
	}

	public Dept(Integer deptno, String dname, String loc) {
		super();
		this.deptno = deptno;
		this.dname = dname;
		this.loc = loc;
	}

	public Integer getDeptno() {
		return deptno;
	}

	public void setDeptno(Integer deptno) {
		this.deptno = deptno;
	}

	public String getDname() {
		return dname;
	}

	public void setDname(String dname) {
		this.dname = dname;
	}

	public String getLoc() {
		return loc;
	}

	public void setLoc(String loc) {
		this.loc = loc;
	}

	@Override
	public String toString() {
		return "Dept [deptno=" + deptno + ", dname=" + dname + ", loc=" + loc + "]";
	}

}

package pojo;

import java.util.Date;

/**
 * 员工类
 */
public class Emp {
	private Integer empno;
	private String ename;
	private String job;
	private Integer mgr;
	private Date hiredate;
	private double sal;
	private double comm;
	private Integer deptno;
	public Integer getEmpno() {
		return empno;
	}
	public void setEmpno(Integer empno) {
		this.empno = empno;
	}
	public String getEname() {
		return ename;
	}
	public void setEname(String ename) {
		this.ename = ename;
	}
	public String getJob() {
		return job;
	}
	public void setJob(String job) {
		this.job = job;
	}
	public Integer getMgr() {
		return mgr;
	}
	public void setMgr(Integer mgr) {
		this.mgr = mgr;
	}
	public Date getHiredate() {
		return hiredate;
	}
	public void setHiredate(Date hiredate) {
		this.hiredate = hiredate;
	}
	public double getSal() {
		return sal;
	}
	public void setSal(double sal) {
		this.sal = sal;
	}
	public double getComm() {
		return comm;
	}
	public void setComm(double comm) {
		this.comm = comm;
	}
	public Integer getDeptno() {
		return deptno;
	}
	public void setDeptno(Integer deptno) {
		this.deptno = deptno;
	}
	@Override
	public String toString() {
		return "Emp [empno=" + empno + ", ename=" + ename + ", job=" + job + ", mgr=" + mgr + ", hiredate=" + hiredate
				+ ", sal=" + sal + ", comm=" + comm + ", deptno=" + deptno + "]";
	}

}

mapper包(xml和对应的接口文件)

DeptMapper.java

package mapper;

import pojo.Dept;

/**
 */
public interface DeptMapper {
	// 增
	int insertDept(Dept dept);

	// 删
	int deleteDept(int id);

	// 改
	int updateDept(Dept dept);

	// 查
	Dept selectByID(int id);

}

EmpMapper.java

package mapper;

import java.util.List;

import pojo.Emp;

/**
 */
public interface EmpMapper {
	//模糊查询返回的是一个结果集
	List<Emp> selectByName(String name);
}

DeptMapper.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="mapper.DeptMapper">

	<!---->
	<insert id="insertDept" parameterType="Dept">
		insert into dept
		(deptno,dname,loc) values(#{deptno},#{dname},#{loc})
	</insert>
	<!---->
	<delete id="deleteDept" parameterType="Integer">

		delete from dept where
		deptno=#{deptno}
	</delete>
	<!---->
	<update id="updateDept" parameterType="Dept">
		update dept set dname = #{dname} where deptno=#{deptno}
	</update>

	<!---->
	<select id="selectByID" parameterType="int" resultType="Dept">
		select *
		from dept where deptno = #{id}
	</select>
</mapper>

EmpMapper.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="mapper.EmpMapper">

	<select id="selectByName" parameterType="string" resultType="Emp">
	select * from emp where ename like '%${value}%'
	</select>
	
	<!-- 连接操作
  #{}:点位符 相当于jdbc? 会生成',使用这个的时候括号里面可以随便写
  ${}: 字符串的拼接 它不会自动生成‘’,这个括号里面只能写value
       简单类型(String, 基本类型)
	查询语句还可以写成select * from emp where ename like "%"#{abc}"%"
	

  -->
</mapper>

test包(测试类)

TestMyBatis

package test;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

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.Before;
import org.junit.Test;

import mapper.DeptMapper;
import mapper.EmpMapper;
import pojo.Dept;
import pojo.Emp;

/**
 * 测试类
 */
public class TestMyBatis {
	private SqlSessionFactory sf = null;
	//将重复操作写在Junit的Before中提前运行
	@Before
	public void start() {
		try {
			String resource = "mybatis-config.xml";
			InputStream is = Resources.getResourceAsStream(resource);
			sf = new SqlSessionFactoryBuilder().build(is);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	// 查询
	@Test
	public void test1() {
		//查询不会对数据造成影响所以这里不用提交
		SqlSession session = sf.openSession();
		// 代理方式
		DeptMapper mapper = session.getMapper(DeptMapper.class);
		Dept dept = mapper.selectByID(10);
		System.out.println(dept);
		session.close();
	}

	// 增加
	@Test
	public void test2() {
		SqlSession session = sf.openSession();
		// 代理方式
		DeptMapper mapper = session.getMapper(DeptMapper.class);
		Dept d = new Dept();
		d.setDeptno(50);
		d.setDname("教务部");
		d.setLoc("武汉");
		int rows = mapper.insertDept(d);
		System.out.println(rows);
		//增加会修改数据库,这里要手动提交
		session.commit();
		session.close();
	}
	
	//修改
	@Test
	public void test3() {
		//修改也会改变数据库,这里使用了自动提交
		SqlSession session = sf.openSession(true);
		// 代理方式
		DeptMapper mapper = session.getMapper(DeptMapper.class);
		Dept d = new Dept();
		d.setDname("学习部");
		d.setDeptno(50);
		int rows = mapper.updateDept(d);
		System.out.println(rows);
		session.close();
	}
	
	//删除
	@Test
	public void test4() {
		SqlSession session = sf.openSession(true);
		// 代理方式
		DeptMapper mapper = session.getMapper(DeptMapper.class);
		int rows = mapper.deleteDept(50);
		System.out.println(rows);
		session.close();
	}
	
	//模糊查询
	@Test
	public void test5() {
		SqlSession session = sf.openSession();
		// 代理方式
		EmpMapper mapper = session.getMapper(EmpMapper.class);
		//返回一个结果集
		List<Emp> list = mapper.selectByName("A");
		System.out.println(list);
		session.close();
	}
}

附:

Mapper接口的开发规范
  • mapper接口的全限定名要和mapper映射文件的namespace的值相同。
  • mapper接口的方法名称要和mapper映射文件中的statement的id相同。
  • mapper接口的方法参数只能有一个,且类型要和mapper映射文件中statement的parameterType的值保持一致。
  • mapper接口的返回值类型要和mapper映射文件中statement的resultType值或resultMap中的type值保持一致。

你可能感兴趣的:(框架)