
一.Mybatis注解開發(fā)單表操作 ***
1.1 MyBatis的常用注解
1.2 注解實現(xiàn)查詢操作
-
表:我們還是用db1中的student表

-
新建mybatis04項目

-
javabean
package com.itheima.bean; ? public class Student { private Integer id; private String name; private Integer age; ? public Student() { } ? public Student(Integer id, String name, Integer age) { this.id = id; this.name = name; this.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; } ? @Override public String toString() { return "Student{" + "id=" + id + ", name='" + name + '\'' + ", age=" + age + '}'; } }
-
創(chuàng)建mapper接口
package com.itheima.mapper; ? import com.itheima.bean.Student; import org.apache.ibatis.annotations.Select; ? import java.util.List; ? public interface StudentMapper {
-
配置MyBatisConfig.xml
-
測試類:com.itheima.test.Test01
@Test public void selectAll() throws Exception{
1.3 注解實現(xiàn)新增操作
-
StudentMapper新增接口方法
-
測試方法
@Test public void insert() throws Exception{
-
返回自動增長主鍵
-
介紹

-
代碼

-
測試

-
結(jié)果

1.4 注解實現(xiàn)修改操作
-
StudentMapper新增接口方法
-
測試方法
@Test public void update() throws Exception{
1.5 注解實現(xiàn)刪除操作
-
StudentMapper新增接口方法
-
測試方法
@Test public void delete() throws Exception{
1.6 注解開發(fā)總結(jié)
注解可以簡化開發(fā)操作,省略映射配置文件的編寫
-
常用注解
@Select(“查詢的 SQL 語句”):執(zhí)行查詢操作注解
@Insert(“查詢的 SQL 語句”):執(zhí)行新增操作注解
@Update(“查詢的 SQL 語句”):執(zhí)行修改操作注解
@Delete(“查詢的 SQL 語句”):執(zhí)行刪除操作注解
-
配置映射關(guān)系
<mappers> <package name="接口所在包"/> </mappers>
二.MyBatis注解開發(fā)的多表操作
2.1 MyBatis的注解實現(xiàn)復雜映射開發(fā)


2.2 一對一查詢
2.2.0 準備工作
-
創(chuàng)建項目: mybatis05

-
javabean - card
package com.itheima.bean; ? public class Card { private Integer id;
-
javabean - person
package com.itheima.bean; ? public class Person { private Integer id;
-
cardMapper接口:我們的核心就是要在Card中做一些處理,實現(xiàn)一對一的查詢
package com.itheima.one_to_one; ? import com.itheima.bean.Card; ? import java.util.List; ? public interface CardMapper {
2.2.1 一對一查詢的模型
一對一查詢的需求:查詢一個用戶信息,與此同時查詢出該用戶對應的身份證信息

2.2.2 一對一查詢的語句
對應的sql語句:
SELECT * FROM card; -- 只根據(jù)這個sql語句只能查詢出來card的數(shù)據(jù)
SELECT * FROM person WHERE id=#{id}; -- 需要根據(jù)card表中查詢出來的pid,再次查詢person數(shù)據(jù)才能將person數(shù)據(jù)也查詢出來
2.2.3 創(chuàng)建PersonMapper接口
public interface PersonMapper {
//根據(jù)id查詢
@Select("SELECT * FROM person WHERE id=#{id}")
public abstract Person selectById(Integer id);
}
2.2.4 使用注解配置CardMapper
public interface CardMapper {
//查詢?nèi)? @Select("SELECT * FROM card")
@Results({
@Result(column = "id",property = "id"),
@Result(column = "number",property = "number"),
@Result(
property = "p", // 被包含對象的變量名
javaType = Person.class, // 被包含對象的實際數(shù)據(jù)類型
column = "pid", // 根據(jù)查詢出的card表中的pid字段來查詢person表
/*
one、@One 一對一固定寫法
select屬性:指定調(diào)用哪個接口中的哪個方法
*/
one = @One(select = "com.itheima.one_to_one.PersonMapper.selectById")
)
})
public abstract List<Card> selectAll();
}
2.2.5 測試類
package com.itheima.one_to_one;
import com.itheima.bean.Card;
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.Test;
import java.io.InputStream;
import java.util.List;
public class Test01 {
@Test
public void selectAll() throws Exception{
//1.加載核心配置文件
InputStream is = Resources.getResourceAsStream("MyBatisConfig.xml");
//2.獲取SqlSession工廠對象
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
//3.通過工廠對象獲取SqlSession對象
SqlSession sqlSession = sqlSessionFactory.openSession(true);
//4.獲取CardMapper接口的實現(xiàn)類對象
CardMapper mapper = sqlSession.getMapper(CardMapper.class);
//5.調(diào)用實現(xiàn)類對象中的方法,接收結(jié)果
List<Card> list = mapper.selectAll();
//6.處理結(jié)果
for (Card card : list) {
System.out.println(card);
}
//7.釋放資源
sqlSession.close();
is.close();
}
}
-
結(jié)果

2.2.6 一對一配置總結(jié)
@Results:封裝映射關(guān)系的父注解。
Result[] value():定義了 Result 數(shù)組
@Result:封裝映射關(guān)系的子注解。
column 屬性:查詢出的表中字段名稱
property 屬性:實體對象中的屬性名稱
javaType 屬性:被包含對象的數(shù)據(jù)類型
one 屬性:一對一查詢固定屬性
@One:一對一查詢的注解。
select 屬性:指定調(diào)用某個接口中的方法
2.2.7 分析

2.3 一對多查詢
2.3.1 一對多查詢的模型
一對多查詢的需求:查詢一個課程,與此同時查詢出該該課程對應的學生信息

2.3.2 一對多查詢的語句
對應的sql語句:
SELECT * FROM classes
SELECT * FROM student WHERE cid=#{cid}
2.3.3 創(chuàng)建StudentMapper接口
public interface StudentMapper {
//根據(jù)cid查詢student表
@Select("SELECT * FROM student WHERE cid=#{cid}")
public abstract List<Student> selectByCid(Integer cid);
}
2.3.4 使用注解配置Mapper
public interface ClassesMapper {
//查詢?nèi)? @Select("SELECT * FROM classes")
@Results({
@Result(column = "id",property = "id"),
@Result(column = "name",property = "name"),
@Result(
property = "students", // 被包含對象的變量名
javaType = List.class, // 被包含對象的實際數(shù)據(jù)類型
column = "id", // 根據(jù)查詢出的classes表的id字段來查詢student表
/*
many、@Many 一對多查詢的固定寫法
select屬性:指定調(diào)用哪個接口中的哪個查詢方法
*/
many = @Many(select = "com.itheima.one_to_many.StudentMapper.selectByCid")
)
})
public abstract List<Classes> selectAll();
}
2.3.5 測試類
public class Test01 {
@Test
public void selectAll() throws Exception{
//1.加載核心配置文件
InputStream is = Resources.getResourceAsStream("MyBatisConfig.xml");
//2.獲取SqlSession工廠對象
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
//3.通過工廠對象獲取SqlSession對象
SqlSession sqlSession = sqlSessionFactory.openSession(true);
//4.獲取ClassesMapper接口的實現(xiàn)類對象
ClassesMapper mapper = sqlSession.getMapper(ClassesMapper.class);
//5.調(diào)用實現(xiàn)類對象中的方法,接收結(jié)果
List<Classes> list = mapper.selectAll();
//6.處理結(jié)果
for (Classes cls : list) {
System.out.println(cls.getId() + "," + cls.getName());
List<Student> students = cls.getStudents();
for (Student student : students) {
System.out.println("\t" + student);
}
}
//7.釋放資源
sqlSession.close();
is.close();
}
}
2.3.6 一對多配置總結(jié)
@Results:封裝映射關(guān)系的父注解。
Result[] value():定義了 Result 數(shù)組
@Result:封裝映射關(guān)系的子注解。
column 屬性:查詢出的表中字段名稱
property 屬性:實體對象中的屬性名稱
javaType 屬性:被包含對象的數(shù)據(jù)類型
many 屬性:一對多查詢固定屬性
@Many:一對多查詢的注解。
select 屬性:指定調(diào)用某個接口中的方法
2.3.7 分析

2.4 多對多查詢
2.4.1 多對多查詢的模型
多對多查詢的需求:查詢學生以及所對應的課程信息

2.4.2 多對多查詢的語句
對應的sql語句:
SELECT DISTINCT s.id,s.name,s.age FROM student s,stu_cr sc WHERE sc.sid=s.id
SELECT c.id,c.name FROM stu_cr sc,course c WHERE sc.cid=c.id AND sc.sid=#{id}
2.4.3 添加CourseMapper 接口方法
public interface CourseMapper {
//根據(jù)學生id查詢所選課程
@Select("SELECT c.id,c.name FROM stu_cr sc,course c WHERE sc.cid=c.id AND sc.sid=#{id}")
public abstract List<Course> selectBySid(Integer id);
}
2.4.4 使用注解配置Mapper
public interface StudentMapper {
//查詢?nèi)? @Select("SELECT DISTINCT s.id,s.name,s.age FROM student s,stu_cr sc WHERE sc.sid=s.id")
@Results({
@Result(column = "id",property = "id"),
@Result(column = "name",property = "name"),
@Result(column = "age",property = "age"),
@Result(
property = "courses", // 被包含對象的變量名
javaType = List.class, // 被包含對象的實際數(shù)據(jù)類型
column = "id", // 根據(jù)查詢出student表的id來作為關(guān)聯(lián)條件,去查詢中間表和課程表
/*
many、@Many 一對多查詢的固定寫法
select屬性:指定調(diào)用哪個接口中的哪個查詢方法
*/
many = @Many(select = "com.itheima.many_to_many.CourseMapper.selectBySid")
)
})
public abstract List<Student> selectAll();
}
2.4.5 測試類
public class Test01 {
@Test
public void selectAll() throws Exception{
//1.加載核心配置文件
InputStream is = Resources.getResourceAsStream("MyBatisConfig.xml");
//2.獲取SqlSession工廠對象
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
//3.通過工廠對象獲取SqlSession對象
SqlSession sqlSession = sqlSessionFactory.openSession(true);
//4.獲取StudentMapper接口的實現(xiàn)類對象
StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
//5.調(diào)用實現(xiàn)類對象中的方法,接收結(jié)果
List<Student> list = mapper.selectAll();
//6.處理結(jié)果
for (Student student : list) {
System.out.println(student.getId() + "," + student.getName() + "," + student.getAge());
List<Course> courses = student.getCourses();
for (Course cours : courses) {
System.out.println("\t" + cours);
}
}
//7.釋放資源
sqlSession.close();
is.close();
}
}
2.4.6 多對多配置總結(jié)
@Results:封裝映射關(guān)系的父注解。
Result[] value():定義了 Result 數(shù)組
@Result:封裝映射關(guān)系的子注解。
column 屬性:查詢出的表中字段名稱
property 屬性:實體對象中的屬性名稱
javaType 屬性:被包含對象的數(shù)據(jù)類型
many 屬性:一對多查詢固定屬性
@Many:一對多查詢的注解。
select 屬性:指定調(diào)用某個接口中的方法
2.4.7 分析

三.構(gòu)建sql
3.1 SQL構(gòu)建對象介紹
-
我們之前通過注解開發(fā)時,相關(guān) SQL 語句都是自己直接拼寫的。一些關(guān)鍵字寫起來比較麻煩、而且容易出錯。
-
MyBatis 給我們提供了 org.apache.ibatis.jdbc.SQL 功能類,專門用于構(gòu)建 SQL 語句

-
創(chuàng)建項目:將之前的注解的所有相關(guān)代碼,配置文件拿過來
-
新建測試類: com.itheima.sql.SqlTest
package com.itheima.sql;
public class SqlTest {
public static void main(String[] args) {
String sql = getSql();
System.out.println(sql);
}
//定義方法,獲取查詢student表的sql語句
public static String getSql() {
String sql = "SELECT * FROM student";
return sql;
}
}
-
修改代碼:使用SQL類通過的方法來編寫sql語句
package com.itheima.sql;
import org.apache.ibatis.jdbc.SQL;
public class SqlTest {
public static void main(String[] args) {
String sql = getSql();
System.out.println(sql);
}
//定義方法,獲取查詢student表的sql語句
/*public static String getSql() {
String sql = "SELECT * FROM student";
return sql;
}*/
public static String getSql() {
String sql = new SQL(){//通過SQL類提供的方法來實現(xiàn)sql語句的編寫
{
SELECT("*");
FROM("student");
}
}.toString();
return sql;
}
}
-
結(jié)果
3.2 查詢功能的實現(xiàn)
-
定義功能類并提供獲取查詢的 SQL 語句的方法
package com.itheima.sql;
import org.apache.ibatis.jdbc.SQL;
public class ReturnSql {
//定義方法,返回查詢的sql語句
public String getSelectAll() {
return new SQL() {
{
SELECT("*");
FROM("student");
}
}.toString();
//以上代碼說明:內(nèi)層的花括號是一個構(gòu)造代碼塊,在實例化一個對象時會先于構(gòu)造方法執(zhí)行,編譯時會將構(gòu)造代碼塊移入構(gòu)造方法中
//如果上述不理解,可以使用以下方式:Builder風格
String sql = new SQL()
.SELECT("*")
.FROM("student")
.toString();
return sql;
}
}
-
@SelectProvider:生成查詢用的 SQL 語句注解(調(diào)用提供sql語句的方法,獲取到查詢的sql語句)
-
修改StudentMapper
//查詢?nèi)?//@Select("SELECT * FROM student")
//注意:method只是指定一個方法的名字,SelectProvider內(nèi)部會自己調(diào)用
@SelectProvider(type = ReturnSql.class , method = "getSelectAll")
public abstract List<Student> selectAll();
-
運行test包中的Test01的selectAll方法,能查詢出數(shù)據(jù)即可
3.3 新增功能的實現(xiàn)
-
定義功能類并提供獲取新增的 SQL 語句的方法,在ReturnSql中增加如下方法:
//定義方法,返回新增的sql語句
public String getInsert(Student stu) {
return new SQL() {
{
INSERT_INTO("student");
INTO_VALUES("#{id},#{name},#{age}");
}
}.toString();
}
-
@InsertProvider:生成新增用的 SQL 語句注解(調(diào)用提供sql語句的方法,獲取到新增的sql語句)
-
修改StudentMapper
//新增功能
//@Insert("INSERT INTO student VALUES (#{id},#{name},#{age})")
@InsertProvider(type = ReturnSql.class , method = "getInsert")
public abstract Integer insert(Student stu);
-
運行test包中的Test01的insert方法,能插入數(shù)據(jù)即可
3.4 修改功能的實現(xiàn)
-
定義功能類并提供獲取修改的 SQL 語句的方法
//定義方法,返回修改的sql語句
public String getUpdate(Student stu) {
return new SQL() {
{
UPDATE("student");
SET("name=#{name}","age=#{age}");
WHERE("id=#{id}");
}
}.toString();
}
-
@UpdateProvider:生成修改用的 SQL 語句注解(調(diào)用提供sql語句的方法,獲取到更新的sql語句)
-
修改StudentMapper
//修改功能
//@Update("UPDATE student SET name=#{name},age=#{age} WHERE id=#{id}")
@UpdateProvider(type = ReturnSql.class , method = "getUpdate")
public abstract Integer update(Student stu);
-
運行test包中的Test01的update方法,能更新數(shù)據(jù)即可
3.5 刪除功能的實現(xiàn)
-
定義功能類并提供獲取刪除的 SQL 語句的方法
//定義方法,返回刪除的sql語句
public String getDelete(Integer id) {
return new SQL() {
{
DELETE_FROM("student");
WHERE("id=#{id}");
}
}.toString();
}
-
@DeleteProvider:生成刪除用的 SQL 語句注解(調(diào)用提供sql語句的方法,獲取到刪除的sql語句)
-
修改StudentMapper
//刪除功能
//@Delete("DELETE FROM student WHERE id=#{id}")
@DeleteProvider(type = ReturnSql.class , method = "getDelete")
public abstract Integer delete(Integer id);
-
運行test包中的Test01的delete方法,能刪除數(shù)據(jù)即可
四.綜合案例 ***
4.1 系統(tǒng)介紹
我們之前在做學生管理系統(tǒng)時,使用的是原始JDBC操作數(shù)據(jù)庫的,操作非常麻煩,現(xiàn)在我們使用MyBatis操作數(shù)據(jù)庫,簡化Dao的開發(fā)。
4.2 環(huán)境搭建
-
創(chuàng)建數(shù)據(jù)庫
-- 創(chuàng)建db3數(shù)據(jù)庫
CREATE DATABASE db3;
-- 使用db3數(shù)據(jù)庫
USE db3;
-- 創(chuàng)建用戶表
CREATE TABLE USER(
uid VARCHAR(50) PRIMARY KEY,-- 用戶id
ucode VARCHAR(50),-- 用戶標識
loginname VARCHAR(100),-- 登錄用戶名
PASSWORD VARCHAR(100),-- 登錄密碼
username VARCHAR(100),-- 用戶名
gender VARCHAR(10),-- 用戶性別
birthday DATE,-- 出生日期
dutydate DATE -- 入職日期
);
-- 添加一條測試數(shù)據(jù)
INSERT INTO USER VALUES ('11111111', 'zhangsan001', 'zhangsan', '1234', '張三', '男', '2008-10-28', '2018-10-28');
-- 創(chuàng)建student表
CREATE TABLE student(
sid INT PRIMARY KEY AUTO_INCREMENT,-- 學生id
NAME VARCHAR(20),-- 學生姓名
age INT,-- 學生年齡
birthday DATE-- 學生生日
);
-- 添加數(shù)據(jù)
INSERT INTO student VALUES (NULL,'張三',23,'1999-09-23'),(NULL,'李四',24,'1998-08-10'),
(NULL,'王五',25,'1996-06-06'),(NULL,'趙六',26,'1994-10-20');
-
將之前的“JDBC基礎(chǔ)網(wǎng)頁版”項目copy過來

-
運行起來:注意這個項目的虛擬目錄必須是/,因為界面中的鏈接寫死了

-
輸入zhangsan,1234,登陸進去,我們現(xiàn)在要處理的是 在校學生管理:

-
在這里,可以對學生進行增刪改查,之前是通過jdbc實現(xiàn)的這些功能,現(xiàn)在我們需要通過mybatis來實現(xiàn)
-
增加jar包:

-
復制相關(guān)的配置文件:log4j和MyBatisConfig

-
修改config.properties(這個其實就是jdbc配置文件)
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://192.168.59.143:3306/db3
username=root
password=itheima
-
修改MyBatisConfig主配置文件:
<!--引入數(shù)據(jù)庫連接的配置文件-->
<properties resource="config.properties"/>
起別名的配置刪掉
<!--配置映射關(guān)系-->
<mappers>
<package name="com.itheima.dao"/>
</mappers>
-
刪除StudentDaoImpl,我們不需要實現(xiàn)類,我們會通過接口代理的方式來實現(xiàn)
-
修改StudentDao,給接口方法通過注解的方式配置sql語句
package com.itheima.dao;
import com.itheima.domain.Student;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import java.util.ArrayList;
/*
Dao層接口
*/
public interface StudentDao {
//查詢所有學生信息
@Select("SELECT * FROM student")
public abstract ArrayList<Student> findAll();
//條件查詢,根據(jù)id獲取學生信息
@Select("SELECT * FROM student WHERE sid=#{sid}")
public abstract Student findById(Integer sid);
//新增學生信息
@Insert("INSERT INTO student VALUES (#{sid},#{name},#{age},#{birthday})")
public abstract int insert(Student stu);
//修改學生信息
@Update("UPDATE student SET name=#{name},age=#{age},birthday=#{birthday} WHERE sid=#{sid}")
public abstract int update(Student stu);
//刪除學生信息
@Delete("DELETE FROM student WHERE sid=#{sid}")
public abstract int delete(Integer sid);
}
-
修改StudentServiceImpl,刪除之前的DaoImpl的邏輯
package com.itheima.service.impl;
import com.itheima.domain.Student;
import com.itheima.service.StudentService;
import java.util.List;
/**
* 學生的業(yè)務層實現(xiàn)類
* @author 黑馬程序員
* @Company http://www.
*/
public class StudentServiceImpl implements StudentService {
@Override
public List<Student> findAll() {
}
@Override
public Student findById(Integer sid) {
}
@Override
public void save(Student student) {
}
@Override
public void update(Student student) {
}
@Override
public void delete(Integer sid) {
}
}
4.3 代碼改造
-
我們主要是將原來的jdbc實現(xiàn)的方式改為mybatis實現(xiàn)
-
新建com.itheima.utils.MyBatisUtils.java
package com.itheima.utils;
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 java.io.IOException;
/*
工具類
*/
public class MyBatisUtils {
// 私有構(gòu)造方法
private MyBatisUtils(){}
// 聲明連接工廠對象
private static SqlSessionFactory sqlSessionFactory;
// 靜態(tài)代碼塊,讀取核心配置文件并工廠對象賦值
static {
try {
sqlSessionFactory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("MyBatisConfig.xml"));
} catch (IOException e) {
e.printStackTrace();
}
}
// 提供靜態(tài)方法,返回SqlSession對象
public static SqlSession getSqlSession() {
return sqlSessionFactory.openSession(true);
}
}
-
修改StudentServiceImpl代碼
package com.itheima.service.impl;
import com.itheima.dao.StudentDao;
import com.itheima.domain.Student;
import com.itheima.service.StudentService;
import com.itheima.utils.MyBatisUtils;
import org.apache.ibatis.session.SqlSession;
import java.util.ArrayList;
import java.util.List;
/**
* 學生的業(yè)務層實現(xiàn)類
* @author 黑馬程序員
* @Company http://www.
*/
public class StudentServiceImpl implements StudentService {
@Override
public List<Student> findAll() {
// 獲取SqlSession對象
SqlSession sqlSession = MyBatisUtils.getSqlSession();
// 獲取StudentDao接口的實現(xiàn)類對象
StudentDao mapper = sqlSession.getMapper(StudentDao.class);
// 調(diào)用實現(xiàn)類對象相應的功能
ArrayList<Student> list = mapper.findAll();
// 釋放資源
sqlSession.close();
// 返回結(jié)果
return list;
}
@Override
public Student findById(Integer sid) {
// 獲取SqlSession對象
SqlSession sqlSession = MyBatisUtils.getSqlSession();
// 獲取StudentDao接口的實現(xiàn)類對象
StudentDao mapper = sqlSession.getMapper(StudentDao.class);
// 調(diào)用實現(xiàn)類對象相應的功能
Student stu = mapper.findById(sid);
// 釋放資源
sqlSession.close();
// 返回結(jié)果
return stu;
}
@Override
public void save(Student student) {
// 獲取SqlSession對象
SqlSession sqlSession = MyBatisUtils.getSqlSession();
// 獲取StudentDao接口的實現(xiàn)類對象
StudentDao mapper = sqlSession.getMapper(StudentDao.class);
// 調(diào)用實現(xiàn)類對象相應的功能
mapper.insert(student);
// 釋放資源
sqlSession.close();
}
@Override
public void update(Student student) {
// 獲取SqlSession對象
SqlSession sqlSession = MyBatisUtils.getSqlSession();
// 獲取StudentDao接口的實現(xiàn)類對象
StudentDao mapper = sqlSession.getMapper(StudentDao.class);
// 調(diào)用實現(xiàn)類對象相應的功能
mapper.update(student);
// 釋放資源
sqlSession.close();
}
@Override
public void delete(Integer sid) {
// 獲取SqlSession對象
SqlSession sqlSession = MyBatisUtils.getSqlSession();
// 獲取StudentDao接口的實現(xiàn)類對象
StudentDao mapper = sqlSession.getMapper(StudentDao.class);
// 調(diào)用實現(xiàn)類對象相應的功能
mapper.delete(sid);
// 釋放資源
sqlSession.close();
}
}
package com.itheima.service.impl;
import com.itheima.dao.StudentDao;
import com.itheima.domain.Student;
import com.itheima.service.StudentService;
import com.itheima.utils.MyBatisUtils;
import org.apache.ibatis.session.SqlSession;
import java.util.ArrayList;
import java.util.List;
/**
* 學生的業(yè)務層實現(xiàn)類
* @author 黑馬程序員
* @Company http://www.
*/
public class StudentServiceImpl implements StudentService {
@Override
public List<Student> findAll() {
// 獲取SqlSession對象
SqlSession sqlSession = MyBatisUtils.getSqlSession();
// 獲取StudentDao接口的實現(xiàn)類對象
StudentDao mapper = sqlSession.getMapper(StudentDao.class);
// 調(diào)用實現(xiàn)類對象相應的功能
ArrayList<Student> list = mapper.findAll();
// 釋放資源
sqlSession.close();
// 返回結(jié)果
return list;
}
@Override
public Student findById(Integer sid) {
// 獲取SqlSession對象
SqlSession sqlSession = MyBatisUtils.getSqlSession();
// 獲取StudentDao接口的實現(xiàn)類對象
StudentDao mapper = sqlSession.getMapper(StudentDao.class);
// 調(diào)用實現(xiàn)類對象相應的功能
Student stu = mapper.findById(sid);
// 釋放資源
sqlSession.close();
// 返回結(jié)果
return stu;
}
@Override
public void save(Student student) {
// 獲取SqlSession對象
SqlSession sqlSession = MyBatisUtils.getSqlSession();
// 獲取StudentDao接口的實現(xiàn)類對象
StudentDao mapper = sqlSession.getMapper(StudentDao.class);
// 調(diào)用實現(xiàn)類對象相應的功能
mapper.insert(student);
// 釋放資源
sqlSession.close();
}
@Override
public void update(Student student) {
// 獲取SqlSession對象
SqlSession sqlSession = MyBatisUtils.getSqlSession();
// 獲取StudentDao接口的實現(xiàn)類對象
StudentDao mapper = sqlSession.getMapper(StudentDao.class);
// 調(diào)用實現(xiàn)類對象相應的功能
mapper.update(student);
// 釋放資源
sqlSession.close();
}
@Override
public void delete(Integer sid) {
// 獲取SqlSession對象
SqlSession sqlSession = MyBatisUtils.getSqlSession();
// 獲取StudentDao接口的實現(xiàn)類對象
StudentDao mapper = sqlSession.getMapper(StudentDao.class);
// 調(diào)用實現(xiàn)類對象相應的功能
mapper.delete(sid);
// 釋放資源
sqlSession.close();
}
}
-
員工管理也有增刪改查,大家可以作為課下作業(yè)

-
|