MyBatis---環境搭建及簡單的SQL對映
資料庫表結構:
一、環境搭建
1、匯入jar包。
2、編寫兩個配置檔案。一個是全域性的mybatis配置檔案,用來指定連線哪個資料庫的。另一個是相當於介面的實現類,第二個配置檔案需要在第一個中註冊。
全域性配置檔案:
<?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="development"> <environment id="development"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="com.mysql.cj.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/test_mybatis?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=UTF-8&useAffectedRows=true"/> <property name="username" value="root"/> <property name="password" value="123456"/> </dataSource> </environment> </environments> <mappers> <!-- 註冊介面的實現 --!> <mapper resource="mybatis/StudentDao.xml"/> </mappers> </configuration>
第二個配置檔案:
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.cj.dao.StudentDao"> <insert id="Add"> insert into student(STUDENT_NAME,STUDENT_NUMBER,STUDENT_AGE) values(#{STUDENT_NAME},#{STUDENT_NUMBER},#{STUDENT_AGE}) </insert> <delete id="Delete"> delete from student where STUDENT_ID=#{id} </delete> <update id="Update"> update student set STUDENT_NAME=#{param2.STUDENT_NAME},STUDENT_NUMBER=#{param2.STUDENT_NUMBER},STUDENT_AGE=#{param2.STUDENT_AGE} where STUDENT_ID=#{param1} </update> <select id="QueryById" resultType="com.cj.entity.Student"> select * from student where STUDENT_ID=#{id} </select> </mapper>
細節:
① 介面實現的配置檔案中namespace用來指定實現的介面的全類名。
② JDBC資料來源配置的URL中拼接引數的時候用&
代替&
。
③ MyBatis框架底層用的還是原生的jdbc,因此當更新的時候要想返回影響的行數,必須帶上useAffectedRows=true
。
④ 增刪改查分別對應一種標籤,只有查詢需要在配置檔案中顯示地指定返回值型別,也會涉及到更多的資料庫查詢細節。
⑤ #{ }這種形式其實是preparedStatement的預編譯模式,用 # 可以取到介面中抽象方法的引數。當引數只有一個
⑥ 可以在全域性配置檔案中用package
完成批量註冊。name指定掃描的包名,某個介面實現的配置檔案必須要和介面放一起,並且檔名要相同。可以在類路徑下面新建出和相應介面相同的包來完成批量註冊的目標。
3、寫介面。
介面程式碼:
public interface StudentDao {
public int Add(Student student);
public boolean Delete(Integer id);
public int Update(Integer id,Student student);
public Student QueryById(Integer id);
}
4、執行helloworld。
測試程式碼:
public class MybatisTest {
@Test
public void test01() {
String resource = "mybatis-config.xml";
SqlSessionFactory sqlSessionFactory = null;
SqlSession sqlSession = null;
InputStream inputStream = null;
try {
inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
sqlSession = sqlSessionFactory.openSession(true); //設定為自動提交
StudentDao studentDao = sqlSession.getMapper(StudentDao.class);
int i = studentDao.Add(new Student(0,"daxx","123",22));
System.out.println(i);
} catch (IOException e) {
e.printStackTrace();
} finally {
// sqlSession.commit();
sqlSession.close();
}
}
@Test
public void test02() {
String resource = "mybatis-config.xml";
SqlSessionFactory sqlSessionFactory = null;
SqlSession sqlSession = null;
InputStream inputStream = null;
try {
inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
sqlSession = sqlSessionFactory.openSession(true); //設定為自動提交
StudentDao studentDao = sqlSession.getMapper(StudentDao.class);
boolean b = studentDao.Delete(5);
System.out.println(b);
} catch (IOException e) {
e.printStackTrace();
} finally {
// sqlSession.commit();
sqlSession.close();
}
}
@Test
public void test03() {
String resource = "mybatis-config.xml";
SqlSessionFactory sqlSessionFactory = null;
SqlSession sqlSession = null;
InputStream inputStream = null;
try {
inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
sqlSession = sqlSessionFactory.openSession(true); //設定為自動提交
StudentDao studentDao = sqlSession.getMapper(StudentDao.class);
int i = studentDao.Update(6,new Student(0,"小米","12345",18));
System.out.println(i);
} catch (IOException e) {
e.printStackTrace();
} finally {
// sqlSession.commit();
sqlSession.close();
}
}
@Test
public void test04() throws IOException {
String resource = "mybatis-config.xml";
SqlSessionFactory sqlSessionFactory = null;
SqlSession sqlSession = null;
InputStream inputStream = null;
try {
inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
sqlSession = sqlSessionFactory.openSession(); //增刪改需要設定自動提交,查詢不需要手動設定
StudentDao studentDao = sqlSession.getMapper(StudentDao.class);
Student student = studentDao.QueryById(7);
System.out.println(student);
} catch (IOException e) {
e.printStackTrace();
} finally {
sqlSession.close();
}
}
}
細節:
查詢出來的結果會自動提交,不需要手動設定。但是增刪改操作需要手動提交,可以在new SqlSession
物件的時候傳入引數true
表示會自動提交,或者呼叫SqlSession 物件.commit()
來提交。
二、簡單的SQL對映
1、獲取自增的主鍵【Mysql、SQL Server】
將自動生成的key賦值給POJO實體類的STUDENT_ID。
<insert id="Add" useGeneratedKeys="true" keyProperty="STUDENT_ID">
insert into student(STUDENT_NAME,#{STUDENT_AGE})
</insert>
@Test
public void test01() {
String resource = "mybatis-config.xml";
SqlSessionFactory sqlSessionFactory = null;
SqlSession sqlSession = null;
InputStream inputStream = null;
try {
inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
sqlSession = sqlSessionFactory.openSession(true); //設定為自動提交
StudentDao studentDao = sqlSession.getMapper(StudentDao.class);
Student student = new Student(0,"大明",21);
int i = studentDao.Add(student);
// System.out.println(i);
System.out.println("自增的id是" + student.getSTUDENT_ID());
} catch (IOException e) {
e.printStackTrace();
} finally {
// sqlSession.commit();
sqlSession.close();
}
}
2、查詢結果封裝成List
public List<Student> QueryAll();
<select id="QueryAll" resultType="com.cj.entity.Student">
select * from student
</select>
@Test
public void test05() throws IOException {
String resource = "mybatis-config.xml";
SqlSessionFactory sqlSessionFactory = null;
SqlSession sqlSession = null;
InputStream inputStream = null;
try {
inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
sqlSession = sqlSessionFactory.openSession(); //增刪改需要設定自動提交,查詢不需要手動設定
StudentDao studentDao = sqlSession.getMapper(StudentDao.class);
List<Student> students = studentDao.QueryAll();
for (Student s : students) {
System.out.println(s);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
sqlSession.close();
}
}
測試結果:
3、查詢結果返回map
@MapKey("STUDENT_ID") //指定表中的某列作為key
public Map<Integer,Student> QueryAllReturnMap();
<select id="QueryAllReturnMap" resultType="com.cj.entity.Student">
select * from student
</select>
@Test
public void test06() throws IOException {
String resource = "mybatis-config.xml";
SqlSessionFactory sqlSessionFactory = null;
SqlSession sqlSession = null;
InputStream inputStream = null;
try {
inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
sqlSession = sqlSessionFactory.openSession(); //增刪改需要設定自動提交,查詢不需要手動設定
StudentDao studentDao = sqlSession.getMapper(StudentDao.class);
Map<Integer,Student> students = studentDao.QueryAllReturnMap();
Set<Integer> set = students.keySet();
for (Integer i : set) {
System.out.println("key=" + i + ",value=" + students.get(i));
}
// System.out.println(students);
} catch (IOException e) {
e.printStackTrace();
} finally {
sqlSession.close();
}
}
測試結果:
4、自定義封裝規則
當資料庫表中的列名和javaBean中成員變數名不一致的時候,不能進行對映,這時候需要起別名或者用resultMap自定義封裝規則。
取別名:
public class Cat {
private int CAT_ID;
private String CAT_NAME;
private int CAT_GENDER;
private int CAT_AGE;
...
}
public interface CatDao {
public Cat QueryById(Integer id);
}
<mapper namespace="com.cj.dao.CatDao">
<select id="QueryById" resultType="com.cj.entity.Cat">
select id CAT_ID,name CAT_NAME,gender CAT_GENDER,age CAT_AGE from cat where id=#{id}
</select>
</mapper>
@Test
public void test07() throws IOException {
String resource = "mybatis-config.xml";
SqlSessionFactory sqlSessionFactory = null;
SqlSession sqlSession = null;
InputStream inputStream = null;
try {
inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
sqlSession = sqlSessionFactory.openSession(); //增刪改需要設定自動提交,查詢不需要手動設定
CatDao catDao = sqlSession.getMapper(CatDao.class);
Cat cat = catDao.QueryById(2);
System.out.println(cat);
} catch (IOException e) {
e.printStackTrace();
} finally {
sqlSession.close();
}
}
測試結果:
自定義封裝規則:
主鍵用id標籤,普通的用result標籤。column指定表的列名,property指定對應實體類中的成員名
。
<mapper namespace="com.cj.dao.CatDao">
<select id="QueryById" resultMap="catMapping">
select * from cat where id=#{id}
</select>
<resultMap id="catMapping" type="com.cj.entity.Cat">
<id column="id" property="CAT_ID"></id>
<result column="name" property="CAT_NAME"></result>
<result column="gender" property="CAT_GENDER"></result>
<result column="age" property="CAT_AGE"></result>
</resultMap>
</mapper>
@Test
public void test07() throws IOException {
String resource = "mybatis-config.xml";
SqlSessionFactory sqlSessionFactory = null;
SqlSession sqlSession = null;
InputStream inputStream = null;
try {
inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
sqlSession = sqlSessionFactory.openSession(); //增刪改需要設定自動提交,查詢不需要手動設定
CatDao catDao = sqlSession.getMapper(CatDao.class);
Cat cat = catDao.QueryById(1);
System.out.println(cat);
} catch (IOException e) {
e.printStackTrace();
} finally {
sqlSession.close();
}
}
測試結果: