1. SpringJdbc
(1)SpringJdbc是什么?
Spring框架对jdbc的封装。
(2)编程步骤
step1.导包spring-webmvc,spring-jdbc,ojdbc,dbcp,junit。
step2.添加spring配置文件。
step3.配置JdbcTemplate。 注:JdbcTemplate把一些重复性的代码(比如获取连接,关闭) 连接,异常处理等等都写好了),我们只需要调用该对象的方法就可以很方便的访问数据库。
step4.调用JdbcTemplate的方法来访问数据库。注:通常将JdbcTemplate注入到DAO。
create table t_emp(id number(8) primary key,name varchar2(20),age number(3)
);
create sequence t_emp_seq;
2. MyBatis
(1)MyBatis是什么?
开源的持久层框架。
注:MyBatis底层仍然是jdbc。
(2)编程步骤
step1. 导包。mybatis,ojdbc,junit
step2. 添加配置文件。注:主要是连接池的配置和映射文件的位置。
step3. 写实体类。 注:实体类的属性名与表的字段名要一样(大小写可以忽略)。
step4. 添加映射文件。 注:里面主要是sql语句。
step5. 调用SqlSession对象提供的方法来访问数据库。
(3)工作原理 (了解)
代码示例
src/main/java
dao (Mapper映射器的接口类)
EmployeeDAO.java
package dao;import java.util.List;
import java.util.Map;import entity.Employee;
import entity.Employee2;/*** Mapper映射器**/
public interface EmployeeDAO {
public void save(Employee e);public List<Employee> findAll();public Employee findById(int id);public void modify(Employee e);public void delete(int id);public Map findById2(int id);public Employee2 findById3(int id);
}
entity
Employee2.java类,测试表里字段名,和数据库中的字段名不一致时情况。
Employee.java
package entity;public class Employee {
private Integer id;private String name;private Integer age;@Overridepublic String toString() {return "Employee [id=" + id + ", name=" + name + ", age=" + 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;}}
Employee2.java
package entity;public class Employee2 {
private Integer empNo;private String ename;private Integer age;@Overridepublic String toString() {return "Employee2 [empNo=" + empNo + ", ename=" + ename + ", age=" + age + "]";}public void setEmpNo(Integer empNo) {this.empNo = empNo;}public void setEname(String ename) {this.ename = ename;}public void setAge(Integer age) {this.age = age;}}
EmpMapper.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"><mapper namespace="dao.EmployeeDAO"><!-- id:要求唯一parameterType:参数类型,要写类的完整的名称。--><insert id="save" parameterType="entity.Employee">INSERT INTO emp_czh VALUES(emp_czh_seq.nextval,#{name},#{age})</insert><!-- resultType:返回类型,要写类的完整的名称。--><select id="findAll" resultType="entity.Employee">SELECT * FROM emp_czh</select><select id="findById" parameterType="int" resultType="entity.Employee">SELECT * FROM emp_czhWHERE id = #{id1}</select><update id="modify" parameterType="entity.Employee">UPDATE emp_czh SET name = #{name},age = #{age} WHERE id = #{id}</update><delete id="delete" parameterType="int">DELETE FROM emp_czh WHERE id = #{id1}</delete><!-- 返回Map类型的结果 --><!-- map是java.util.Map的简写形式--><select id="findById2" parameterType="int"resultType="map">SELECT * FROM emp_czh WHERE id = #{id1}</select><!-- resultMap告诉mybatis表的字段名与实体类的属性名的对应关系。(如果表的字段名与属性名相同,则不用写了)--><resultMap type="entity.Employee2" id="empResultMap"><result property="empNo" column="id"/><result property="ename" column="name"/></resultMap><select id="findById3" parameterType="int"resultMap="empResultMap">SELECT * FROM emp_czh WHERE id = #{id1}</select>
</mapper>
src/main/resources
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" /><!-- mybatis自带的连接池 --><dataSource type="POOLED"><property name="driver" value="oracle.jdbc.driver.OracleDriver" /><property name="url"value="jdbc:oracle:thin:@192.168.201.227:1521:orcl" /><property name="username" value="openlab" /><property name="password" value="open123" /></dataSource></environment></environments><!-- 告诉mybatis,映射文件的位置 --><mappers><mapper resource="entity/EmpMapper.xml" /></mappers></configuration>
src/test/java
test
TestCase2.java测试使用映射器的情况。
TestCase.java
package test;import java.util.List;
import java.util.Map;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 entity.Employee;
import entity.Employee2;public class TestCase {
private SqlSession session;@Before//执行测试方法(比如test1方法)之前,//@Before方法会先执行。public void init(){/** 先要获得SqlSession,然后再调用* SqlSession提供的方法来访问数据库。*///step1. 创建SqlSessionFactoryBuilder对象SqlSessionFactoryBuilder ssfb = new SqlSessionFactoryBuilder();//step2. 创建SqlSessionFactory对象SqlSessionFactory ssf = ssfb.build(TestCase.class.getClassLoader().getResourceAsStream("SqlMapConfig.xml"));//step3. 创建SqlSession对象session = ssf.openSession();}@Testpublic void test1(){//step4. 调用SqlSession提供的方法访问数据库Employee e = new Employee();e.setName("Tom");e.setAge(22);session.insert("test.save", e);//step5. 提交事务//session.commit();//step6.关闭sessionsession.close();}@Testpublic void test2(){List<Employee> employees = session.selectList("test.findAll");System.out.println(employees);session.close();}@Testpublic void test3(){Employee e = session.selectOne("test.findById", 5);System.out.println(e);session.close();}@Testpublic void test4(){Employee e = session.selectOne("test.findById", 5);e.setAge(e.getAge() + 20);session.update("test.modify",e);session.commit();session.close();}@Testpublic void test5(){session.delete("test.delete", 5);session.commit();session.close();}@Test//测试 返回Map类型的结果public void test6(){Map data = session.selectOne("test.findById2", 6);/** oracle数据库中,表的字段名都是大写的。*/System.out.println(data.get("NAME"));session.close();}@Test//测试 解决实体类属性与表的字段名不一致的情况public void test7(){Employee2 e = session.selectOne("test.findById3",6);System.out.println(e);session.close();}
}
TestCase2.java
package test;import java.util.List;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 dao.EmployeeDAO;
import entity.Employee;public class TestCase2 {
private SqlSession session;@Before//执行测试方法(比如test1方法)之前,//@Before方法会先执行。public void init(){/** 先要获得SqlSession,然后再调用* SqlSession提供的方法来访问数据库。*///step1. 创建SqlSessionFactoryBuilder对象SqlSessionFactoryBuilder ssfb = new SqlSessionFactoryBuilder();//step2. 创建SqlSessionFactory对象SqlSessionFactory ssf = ssfb.build(TestCase.class.getClassLoader().getResourceAsStream("SqlMapConfig.xml"));//step3. 创建SqlSession对象session = ssf.openSession();}@Testpublic void test1(){//获得符合映射器(接口)要求的对象EmployeeDAO dao = session.getMapper(EmployeeDAO.class);Employee e = new Employee();e.setName("Eric");e.setAge(23);dao.save(e);//仍然需要提交事务session.commit();session.close();}@Testpublic void test2(){EmployeeDAO dao = session.getMapper(EmployeeDAO.class);List<Employee> employees = dao.findAll();System.out.println(employees);session.close();}@Testpublic void test3(){EmployeeDAO dao = session.getMapper(EmployeeDAO.class);Employee e = dao.findById(6);System.out.println(e);session.close();}
}
pom.xml
<dependencies><dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId><version>3.2.8</version></dependency><dependency><groupId>com.oracle</groupId><artifactId>ojdbc14</artifactId><version>10.2.0.4.0</version></dependency><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.12</version></dependency></dependencies>