最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Mybatis注解開發(fā)單表、多表操作的實(shí)現(xiàn)代碼

 更新時(shí)間:2021年02月25日 14:55:21   作者:學(xué)渣突然想學(xué)java  
這篇文章主要介紹了Mybatis高級:Mybatis注解開發(fā)單表操作,Mybatis注解開發(fā)多表操作,構(gòu)建sql語句,綜合案例學(xué)生管理系統(tǒng)使用接口注解方式優(yōu)化,需要的朋友可以參考下

一.Mybatis注解開發(fā)單表操作 ***

1.1 MyBatis的常用注解

之前我們在Mapper映射文件中編寫的sql語句已經(jīng)各種配置,其實(shí)是比較麻煩的

而這幾年來注解開發(fā)越來越流行,Mybatis也可以使用注解開發(fā)方式,這樣我們就可以減少編寫Mapper映射文件了

常用注解

@Select(“查詢的 SQL 語句”):執(zhí)行查詢操作注解

@Insert(“查詢的 SQL 語句”):執(zhí)行新增操作注解

@Update(“查詢的 SQL 語句”):執(zhí)行修改操作注解

@Delete(“查詢的 SQL 語句”):執(zhí)行刪除操作注解

1.2 注解實(shí)現(xiàn)查詢操作

表:我們還是用db1中的student表

新建mybatis04項(xiàng)目

  • 導(dǎo)入所需要的包
  • 配置相關(guān)的幾個(gè)配置文件(配置文件的內(nèi)容與之前項(xiàng)目都一致,這里就不在羅列)
  • 新建所需要的包

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 {
 //查詢?nèi)?
 @Select("SELECT * FROM student")
 public abstract List<Student> selectAll();
}

配置MyBatisConfig.xml

<!--配置映射關(guān)系:這里已經(jīng)沒有Mapper映射文件了,但是我們需要配置mapper接口所在的包-->
<mappers>
 <package name="com.itheima.mapper"/>
</mappers>
<!--其實(shí)是注解的方式幫助我們生成了映射文件,所以我們依然是在mappers節(jié)點(diǎn)里配置-->

測試類:com.itheima.test.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接口的實(shí)現(xiàn)類對象
 StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
​
 //5.調(diào)用實(shí)現(xiàn)類對象中的方法,接收結(jié)果
 List<Student> list = mapper.selectAll();
​
 //6.處理結(jié)果
 for (Student student : list) {
 System.out.println(student);
 }
 }

注意:

修改MyBatis的核心配置文件,我們使用了注解替代的映射文件,所以我們只需要加載使用了注解的Mapper接口即可

<mappers>
 <!--掃描使用注解的類-->
 <mapper class="com.itheima.mapper.UserMapper"></mapper>
</mappers>

或者指定掃描包含映射關(guān)系的接口所在的包也可以

<mappers>
 <!--掃描使用注解的類所在的包-->
 <package name="com.itheima.mapper"></package>
</mappers>

1.3 注解實(shí)現(xiàn)新增操作

StudentMapper新增接口方法

//新增操作: sql的參數(shù)與之前的寫法一致,從insert方法的參數(shù)中獲取對應(yīng)屬性值
@Insert("INSERT INTO student VALUES (#{id},#{name},#{age})")
public abstract Integer insert(Student stu);

測試方法

@Test
public void insert() 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接口的實(shí)現(xiàn)類對象
 StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
​
 //5.調(diào)用實(shí)現(xiàn)類對象中的方法,接收結(jié)果
 Student stu = new Student(4,"趙六",26);
 Integer result = mapper.insert(stu);
​
 //6.處理結(jié)果
 System.out.println(result);
​
 //7.釋放資源
 sqlSession.close();
 is.close();
}

返回自動增長主鍵

介紹

代碼

  • 在insert注解之上添加Options注解
  • 指定主鍵列為id,主鍵屬性為id(意味會將注解列id最終的自增結(jié)果返回,并且賦值給stu的id屬性)

測試

在mapper.insert(stu)之后,會將操作結(jié)果返回,并且也會對stu本身的id進(jìn)行賦值

結(jié)果

1.4 注解實(shí)現(xiàn)修改操作

StudentMapper新增接口方法

//修改操作
@Update("UPDATE student SET name=#{name},age=#{age} WHERE id=#{id}")
public abstract Integer update(Student stu);

測試方法

@Test
public void update() 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接口的實(shí)現(xiàn)類對象
 StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
​
 //5.調(diào)用實(shí)現(xiàn)類對象中的方法,接收結(jié)果
 Student stu = new Student(4,"趙六",36);
 Integer result = mapper.update(stu);
​
 //6.處理結(jié)果
 System.out.println(result);
​
 //7.釋放資源
 sqlSession.close();
 is.close();
}

1.5 注解實(shí)現(xiàn)刪除操作

StudentMapper新增接口方法

//刪除操作
@Delete("DELETE FROM student WHERE id=#{id}")
public abstract Integer delete(Integer id);

測試方法

@Test
public void delete() 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接口的實(shí)現(xiàn)類對象
 StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
​
 //5.調(diào)用實(shí)現(xiàn)類對象中的方法,接收結(jié)果
 Integer result = mapper.delete(4);
​
 //6.處理結(jié)果
 System.out.println(result);
​
 //7.釋放資源
 sqlSession.close();
 is.close();
}

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的注解實(shí)現(xiàn)復(fù)雜映射開發(fā)

  • 實(shí)現(xiàn)復(fù)雜關(guān)系映射之前我們可以在映射文件中通過配置 <resultMap> 來實(shí)現(xiàn),
  • 使用注解開發(fā)后,我們可以使用@Results注解,@Result注解,@One注解,@Many注解組合完成復(fù)雜關(guān)系的配置

2.2 一對一查詢

2.2.0 準(zhǔn)備工作

創(chuàng)建項(xiàng)目: mybatis05

javabean - card

package com.itheima.bean;
​
public class Card {
 private Integer id; //主鍵id
 private String number; //身份證號
​
 private Person p; //所屬人的對象
​
 public Card() {
 }
​
 public Card(Integer id, String number, Person p) {
 this.id = id;
 this.number = number;
 this.p = p;
 }
​
 public Integer getId() {
 return id;
 }
​
 public void setId(Integer id) {
 this.id = id;
 }
​
 public String getNumber() {
 return number;
 }
​
 public void setNumber(String number) {
 this.number = number;
 }
​
 public Person getP() {
 return p;
 }
​
 public void setP(Person p) {
 this.p = p;
 }
​
 @Override
 public String toString() {
 return "Card{" +
 "id=" + id +
 ", number='" + number + '\'' +
 ", p=" + p +
 '}';
 }
}

javabean - person

package com.itheima.bean;
​
public class Person {
 private Integer id; //主鍵id
 private String name; //人的姓名
 private Integer age; //人的年齡
​
 public Person() {
 }
​
 public Person(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 "Person{" +
 "id=" + id +
 ", name='" + name + '\'' +
 ", age=" + age +
 '}';
 }
}

cardMapper接口:我們的核心就是要在Card中做一些處理,實(shí)現(xiàn)一對一的查詢

package com.itheima.one_to_one;
​
import com.itheima.bean.Card;
​
import java.util.List;
​
public interface CardMapper {
 //查詢?nèi)?
 public abstract List<Card> selectAll();
}

2.2.1 一對一查詢的模型

一對一查詢的需求:查詢一個(gè)用戶信息,與此同時(shí)查詢出該用戶對應(yīng)的身份證信息

2.2.2 一對一查詢的語句

對應(yīng)的sql語句:

SELECT * FROM card; -- 只根據(jù)這個(gè)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í)際數(shù)據(jù)類型
  column = "pid", // 根據(jù)查詢出的card表中的pid字段來查詢person表
  /*
  one、@One 一對一固定寫法
  select屬性:指定調(diào)用哪個(gè)接口中的哪個(gè)方法
  */
  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接口的實(shí)現(xiàn)類對象
 CardMapper mapper = sqlSession.getMapper(CardMapper.class);

 //5.調(diào)用實(shí)現(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 屬性:實(shí)體對象中的屬性名稱
	javaType 屬性:被包含對象的數(shù)據(jù)類型
	one 屬性:一對一查詢固定屬性
 @One:一對一查詢的注解。
	select 屬性:指定調(diào)用某個(gè)接口中的方法

2.2.7 分析

2.3 一對多查詢

2.3.1 一對多查詢的模型

一對多查詢的需求:查詢一個(gè)課程,與此同時(shí)查詢出該該課程對應(yīng)的學(xué)生信息

2.3.2 一對多查詢的語句

對應(yīng)的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í)際數(shù)據(jù)類型
  column = "id", // 根據(jù)查詢出的classes表的id字段來查詢student表
  /*
  many、@Many 一對多查詢的固定寫法
  select屬性:指定調(diào)用哪個(gè)接口中的哪個(gè)查詢方法
  */
  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接口的實(shí)現(xiàn)類對象
 ClassesMapper mapper = sqlSession.getMapper(ClassesMapper.class);

 //5.調(diào)用實(shí)現(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 屬性:實(shí)體對象中的屬性名稱
	javaType 屬性:被包含對象的數(shù)據(jù)類型
	many 屬性:一對多查詢固定屬性
@Many:一對多查詢的注解。
	select 屬性:指定調(diào)用某個(gè)接口中的方法

2.3.7 分析

2.4 多對多查詢

2.4.1 多對多查詢的模型

多對多查詢的需求:查詢學(xué)生以及所對應(yīng)的課程信息

2.4.2 多對多查詢的語句

對應(yīng)的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ù)學(xué)生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í)際數(shù)據(jù)類型
  column = "id", // 根據(jù)查詢出student表的id來作為關(guān)聯(lián)條件,去查詢中間表和課程表
  /*
  many、@Many 一對多查詢的固定寫法
  select屬性:指定調(diào)用哪個(gè)接口中的哪個(gè)查詢方法
  */
  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接口的實(shí)現(xiàn)類對象
 StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);

 //5.調(diào)用實(shí)現(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 屬性:實(shí)體對象中的屬性名稱
	javaType 屬性:被包含對象的數(shù)據(jù)類型
	many 屬性:一對多查詢固定屬性
@Many:一對多查詢的注解。
	select 屬性:指定調(diào)用某個(gè)接口中的方法

2.4.7 分析

三.構(gòu)建sql

3.1 SQL構(gòu)建對象介紹

我們之前通過注解開發(fā)時(shí),相關(guān) SQL 語句都是自己直接拼寫的。一些關(guān)鍵字寫起來比較麻煩、而且容易出錯(cuò)。

MyBatis 給我們提供了 org.apache.ibatis.jdbc.SQL 功能類,專門用于構(gòu)建 SQL 語句

創(chuàng)建項(xià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中的關(guān)鍵字較多時(shí),就可能會寫錯(cuò)

修改代碼:使用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類提供的方法來實(shí)現(xiàn)sql語句的編寫
 {
 SELECT("*");
 FROM("student");
 }
 }.toString();

 return sql;
 }
}

結(jié)果

3.2 查詢功能的實(shí)現(xiàn)

定義功能類并提供獲取查詢的 SQL 語句的方法

新建類:com.itheima.sql.ReturnSql,定義獲取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è)構(gòu)造代碼塊,在實(shí)例化一個(gè)對象時(shí)會先于構(gòu)造方法執(zhí)行,編譯時(shí)會將構(gòu)造代碼塊移入構(gòu)造方法中
 //如果上述不理解,可以使用以下方式:Builder風(fēng)格
 String sql = new SQL()
 .SELECT("*")
 .FROM("student")
 .toString();
 return sql;
 }
}
  • 那么如何獲取這個(gè)提供了sql語句的方法呢?
  • 之前是在Mapper接口中直接通過注解(@Select,@Insert等)來設(shè)置的sql
  • 現(xiàn)在有提供了sql語句的方法,如何獲取呢?
  • 通過@SelectProvider注解來獲取

@SelectProvider:生成查詢用的 SQL 語句注解( 調(diào)用提供sql語句的方法,獲取到查詢的sql語句

type 屬性:用于指定生成 SQL 語句功能的類對象

method 屬性:用于指定類中要執(zhí)行獲取sql語句的方法 (指定方法名,不加小括號)

修改StudentMapper

//查詢?nèi)?
//@Select("SELECT * FROM student")
//注意:method只是指定一個(gè)方法的名字,SelectProvider內(nèi)部會自己調(diào)用
@SelectProvider(type = ReturnSql.class , method = "getSelectAll")
public abstract List<Student> selectAll();

運(yùn)行test包中的Test01的selectAll方法,能查詢出數(shù)據(jù)即可

3.3 新增功能的實(shí)現(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語句

type 屬性:生成 SQL 語句功能類對象

method 屬性:指定調(diào)用方法

修改StudentMapper

//新增功能
//@Insert("INSERT INTO student VALUES (#{id},#{name},#{age})")
@InsertProvider(type = ReturnSql.class , method = "getInsert")
public abstract Integer insert(Student stu);

運(yùn)行test包中的Test01的insert方法,能插入數(shù)據(jù)即可

3.4 修改功能的實(shí)現(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語句

type 屬性:生成 SQL 語句功能類對象

method 屬性:指定調(diào)用方法

修改StudentMapper

//修改功能
//@Update("UPDATE student SET name=#{name},age=#{age} WHERE id=#{id}")
@UpdateProvider(type = ReturnSql.class , method = "getUpdate")
public abstract Integer update(Student stu);

運(yùn)行test包中的Test01的update方法,能更新數(shù)據(jù)即可

3.5 刪除功能的實(shí)現(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語句

type 屬性:生成 SQL 語句功能類對象

method 屬性:指定調(diào)用方法

修改StudentMapper

//刪除功能
//@Delete("DELETE FROM student WHERE id=#{id}")
@DeleteProvider(type = ReturnSql.class , method = "getDelete")
public abstract Integer delete(Integer id);

運(yùn)行test包中的Test01的delete方法,能刪除數(shù)據(jù)即可

四.綜合案例 ***

4.1 系統(tǒng)介紹

我們之前在做學(xué)生管理系統(tǒng)時(shí),使用的是原始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),		-- 用戶標(biāo)識
	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,	-- 學(xué)生id
	NAME VARCHAR(20),			-- 學(xué)生姓名
	age INT,				-- 學(xué)生年齡
	birthday DATE				-- 學(xué)生生日
);

-- 添加數(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)頁版”項(xiàng)目copy過來

運(yùn)行起來:注意這個(gè)項(xiàng)目的虛擬目錄必須是/,因?yàn)榻缑嬷械逆溄訉懰懒?/p>

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

在這里,可以對學(xué)生進(jìn)行增刪改查,之前是通過jdbc實(shí)現(xiàn)的這些功能,現(xiàn)在我們需要通過mybatis來實(shí)現(xiàn)

增加jar包:

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

修改config.properties(這個(gè)其實(shí)就是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,我們不需要實(shí)現(xiàn)類,我們會通過接口代理的方式來實(shí)現(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 {
 //查詢所有學(xué)生信息
 @Select("SELECT * FROM student")
 public abstract ArrayList<Student> findAll();

 //條件查詢,根據(jù)id獲取學(xué)生信息
 @Select("SELECT * FROM student WHERE sid=#{sid}")
 public abstract Student findById(Integer sid);

 //新增學(xué)生信息
 @Insert("INSERT INTO student VALUES (#{sid},#{name},#{age},#{birthday})")
 public abstract int insert(Student stu);

 //修改學(xué)生信息
 @Update("UPDATE student SET name=#{name},age=#{age},birthday=#{birthday} WHERE sid=#{sid}")
 public abstract int update(Student stu);

 //刪除學(xué)生信息
 @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;

/**
 * 學(xué)生的業(yè)務(wù)層實(shí)現(xiàn)類
 * @author 黑馬程序員
 * @Company http://www.itheima.com
 */
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實(shí)現(xiàn)的方式改為mybatis實(shí)現(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;

/**
 * 學(xué)生的業(yè)務(wù)層實(shí)現(xiàn)類
 * @author 黑馬程序員
 * @Company http://www.itheima.com
 */
public class StudentServiceImpl implements StudentService {

 @Override
 public List<Student> findAll() {
 // 獲取SqlSession對象
 SqlSession sqlSession = MyBatisUtils.getSqlSession();

 // 獲取StudentDao接口的實(shí)現(xiàn)類對象
 StudentDao mapper = sqlSession.getMapper(StudentDao.class);

 // 調(diào)用實(shí)現(xiàn)類對象相應(yīng)的功能
 ArrayList<Student> list = mapper.findAll();

 // 釋放資源
 sqlSession.close();

 // 返回結(jié)果
 return list;
 }

 @Override
 public Student findById(Integer sid) {
 // 獲取SqlSession對象
 SqlSession sqlSession = MyBatisUtils.getSqlSession();

 // 獲取StudentDao接口的實(shí)現(xiàn)類對象
 StudentDao mapper = sqlSession.getMapper(StudentDao.class);

 // 調(diào)用實(shí)現(xiàn)類對象相應(yīng)的功能
 Student stu = mapper.findById(sid);

 // 釋放資源
 sqlSession.close();

 // 返回結(jié)果
 return stu;
 }

 @Override
 public void save(Student student) {
 // 獲取SqlSession對象
 SqlSession sqlSession = MyBatisUtils.getSqlSession();

 // 獲取StudentDao接口的實(shí)現(xiàn)類對象
 StudentDao mapper = sqlSession.getMapper(StudentDao.class);

 // 調(diào)用實(shí)現(xiàn)類對象相應(yīng)的功能
 mapper.insert(student);

 // 釋放資源
 sqlSession.close();

 }

 @Override
 public void update(Student student) {
 // 獲取SqlSession對象
 SqlSession sqlSession = MyBatisUtils.getSqlSession();

 // 獲取StudentDao接口的實(shí)現(xiàn)類對象
 StudentDao mapper = sqlSession.getMapper(StudentDao.class);

 // 調(diào)用實(shí)現(xiàn)類對象相應(yīng)的功能
 mapper.update(student);

 // 釋放資源
 sqlSession.close();
 }

 @Override
 public void delete(Integer sid) {
 // 獲取SqlSession對象
 SqlSession sqlSession = MyBatisUtils.getSqlSession();

 // 獲取StudentDao接口的實(shí)現(xiàn)類對象
 StudentDao mapper = sqlSession.getMapper(StudentDao.class);

 // 調(diào)用實(shí)現(xiàn)類對象相應(yīng)的功能
 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;

/**
 * 學(xué)生的業(yè)務(wù)層實(shí)現(xiàn)類
 * @author 黑馬程序員
 * @Company http://www.itheima.com
 */
public class StudentServiceImpl implements StudentService {

 @Override
 public List<Student> findAll() {
 // 獲取SqlSession對象
 SqlSession sqlSession = MyBatisUtils.getSqlSession();

 // 獲取StudentDao接口的實(shí)現(xiàn)類對象
 StudentDao mapper = sqlSession.getMapper(StudentDao.class);

 // 調(diào)用實(shí)現(xiàn)類對象相應(yīng)的功能
 ArrayList<Student> list = mapper.findAll();

 // 釋放資源
 sqlSession.close();

 // 返回結(jié)果
 return list;
 }

 @Override
 public Student findById(Integer sid) {
 // 獲取SqlSession對象
 SqlSession sqlSession = MyBatisUtils.getSqlSession();

 // 獲取StudentDao接口的實(shí)現(xiàn)類對象
 StudentDao mapper = sqlSession.getMapper(StudentDao.class);

 // 調(diào)用實(shí)現(xiàn)類對象相應(yīng)的功能
 Student stu = mapper.findById(sid);

 // 釋放資源
 sqlSession.close();

 // 返回結(jié)果
 return stu;
 }

 @Override
 public void save(Student student) {
 // 獲取SqlSession對象
 SqlSession sqlSession = MyBatisUtils.getSqlSession();

 // 獲取StudentDao接口的實(shí)現(xiàn)類對象
 StudentDao mapper = sqlSession.getMapper(StudentDao.class);

 // 調(diào)用實(shí)現(xiàn)類對象相應(yīng)的功能
 mapper.insert(student);

 // 釋放資源
 sqlSession.close();

 }

 @Override
 public void update(Student student) {
 // 獲取SqlSession對象
 SqlSession sqlSession = MyBatisUtils.getSqlSession();

 // 獲取StudentDao接口的實(shí)現(xiàn)類對象
 StudentDao mapper = sqlSession.getMapper(StudentDao.class);

 // 調(diào)用實(shí)現(xiàn)類對象相應(yīng)的功能
 mapper.update(student);

 // 釋放資源
 sqlSession.close();
 }

 @Override
 public void delete(Integer sid) {
 // 獲取SqlSession對象
 SqlSession sqlSession = MyBatisUtils.getSqlSession();

 // 獲取StudentDao接口的實(shí)現(xiàn)類對象
 StudentDao mapper = sqlSession.getMapper(StudentDao.class);

 // 調(diào)用實(shí)現(xiàn)類對象相應(yīng)的功能
 mapper.delete(sid);

 // 釋放資源
 sqlSession.close();
 }
}

員工管理也有增刪改查,大家可以作為課下作業(yè)

到此這篇關(guān)于Mybatis注解開發(fā)單表、多表操作的實(shí)現(xiàn)代碼的文章就介紹到這了,更多相關(guān)Mybatis注解開發(fā)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • 關(guān)于SpringBoot配置文件application.properties的路徑問題

    關(guān)于SpringBoot配置文件application.properties的路徑問題

    這篇文章主要介紹了關(guān)于SpringBoot配置文件application.properties的路徑問題,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2022-08-08
  • Java之Spring Bean 作用域和生命周期

    Java之Spring Bean 作用域和生命周期

    這篇文章主要介紹了Java Bean的作用域和生命周期,Bean 的作用域是指 Bean 在 Spring 整個(gè)框架中的某種行為模式,所謂的?命周期指的是?個(gè)對象從誕?到銷毀的整個(gè)?命過程,我們把這個(gè)過程就叫做?個(gè)對象的?命周期,感興趣的同學(xué)可以參考閱讀
    2023-04-04
  • IDEA配置碼云Gitee的使用詳解

    IDEA配置碼云Gitee的使用詳解

    這篇文章主要介紹了IDEA配置碼云Gitee的使用,本文通過圖文并茂的形式給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2020-12-12
  • Java 輸入多行字符串或者多個(gè)int數(shù)值的方法

    Java 輸入多行字符串或者多個(gè)int數(shù)值的方法

    今天小編就為大家分享一篇Java 輸入多行字符串或者多個(gè)int數(shù)值的方法,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2018-07-07
  • Java中Stream流的peek方法詳解及常見使用場景

    Java中Stream流的peek方法詳解及常見使用場景

    這篇文章主要介紹了Java中Stream流的peek方法詳解及常見使用場景的相關(guān)資料,peek()方法是一個(gè)中間操作,用于在流的每個(gè)元素上執(zhí)行一個(gè)操作,而不會改變流中的元素或中斷流的處理,需要的朋友可以參考下
    2025-03-03
  • SpringBoot實(shí)現(xiàn)文件的上傳、下載和預(yù)覽功能

    SpringBoot實(shí)現(xiàn)文件的上傳、下載和預(yù)覽功能

    在Spring Boot項(xiàng)目中實(shí)現(xiàn)文件的上傳、下載和預(yù)覽功能,可以通過使用Spring MVC的MultipartFile接口來處理文件上傳,并使用HttpServletResponse或Resource來實(shí)現(xiàn)文件下載和預(yù)覽,下面是如何實(shí)現(xiàn)這些功能的完整示例,需要的朋友可以參考下
    2024-08-08
  • Maven項(xiàng)目外部jar包導(dǎo)入的實(shí)現(xiàn)示例

    Maven項(xiàng)目外部jar包導(dǎo)入的實(shí)現(xiàn)示例

    在Maven項(xiàng)目里,我們經(jīng)常需要導(dǎo)入jar包依賴,本文主要介紹了Maven項(xiàng)目外部jar包導(dǎo)入的實(shí)現(xiàn)示例,具有一定的參考價(jià)值,感興趣的可以了解一下
    2024-08-08
  • Nacos配置中心搭建及動態(tài)刷新配置及踩坑記錄

    Nacos配置中心搭建及動態(tài)刷新配置及踩坑記錄

    這篇文章主要介紹了Nacos配置中心搭建及動態(tài)刷新配置及踩坑記錄,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2022-11-11
  • Java函數(shù)式編程(五):閉包

    Java函數(shù)式編程(五):閉包

    這篇文章主要介紹了Java函數(shù)式編程(五):閉包,本文是系列文章的第5篇,其它篇章請參閱相關(guān)文章,需要的朋友可以參考下
    2014-09-09
  • Spring Boot+maven打war包的方法

    Spring Boot+maven打war包的方法

    這篇文章主要介紹了Spring Boot+maven打war包的方法,本文通過實(shí)例代碼相結(jié)合的形式給大家介紹的非常詳細(xì),需要的朋友參考下吧
    2018-05-05

最新評論

聂荣县| 曲沃县| 鲜城| 睢宁县| 包头市| 衡水市| 汉川市| 藁城市| 高平市| 甘谷县| 南木林县| 汉阴县| 宁海县| 西乌| 霞浦县| 苏尼特左旗| 泗洪县| 邵阳县| 静海县| 重庆市| 迁安市| 成都市| 阳山县| 昌都县| 临夏县| 新津县| 晋城| 祥云县| 甘德县| 威远县| 兰溪市| 肇源县| 铜川市| 普宁市| 二手房| 武隆县| 涞源县| 大同县| 抚顺市| 嘉禾县| 周宁县|