Mybatis示例講解注解開發(fā)中的單表操作
Mybatis注解開發(fā)單表操作
MyBatis的常用注解
Mybatis也可以使用注解開發(fā)方式,這樣我們就可以減少編寫Mapper映射文件了。我們先圍繞一些基本的CRUD來學(xué)習(xí),再學(xué)習(xí)復(fù)雜映射多表操作。
| 注解 | 說明 |
|---|---|
| @Insert | 實現(xiàn)新增 |
| @Update | 實現(xiàn)更新 |
| @Delete | 實現(xiàn)刪除 |
| @Select | 實現(xiàn)查詢 |
| @Result | 實現(xiàn)結(jié)果集封裝 |
| @Results | 可以與@Result 一起使用,封裝多個結(jié)果集 |
| @One | 實現(xiàn)一對一結(jié)果集封裝 |
| @Many | 實現(xiàn)一對多結(jié)果集封 |
MyBatis的增刪改查
我們完成簡單的student表的增刪改查的操作
步驟一:創(chuàng)建mapper接口
public interface StudentMapper {
//查詢?nèi)?
@Select("SELECT * FROM student")
public abstract List<Student> selectAll();
//新增操作
@Insert("INSERT INTO student VALUES (#{id},#{name},#{age})")
public abstract Integer insert(Student stu);
//修改操作
@Update("UPDATE student SET name=#{name},age=#{age} WHERE id=#{id}")
public abstract Integer update(Student stu);
//刪除操作
@Delete("DELETE FROM student WHERE id=#{id}")
public abstract Integer delete(Integer id);
}步驟二:測試類
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);
}
//7.釋放資源
sqlSession.close();
is.close();
}
@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接口的實現(xiàn)類對象
StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
//5.調(diào)用實現(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();
}
@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接口的實現(xiàn)類對象
StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
//5.調(diào)用實現(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();
}
@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接口的實現(xiàn)類對象
StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
//5.調(diào)用實現(xiàn)類對象中的方法,接收結(jié)果
Integer result = mapper.delete(4);
//6.處理結(jié)果
System.out.println(result);
//7.釋放資源
sqlSession.close();
is.close();
}
}例如運行test1結(jié)果如下:

注意:
修改MyBatis的核心配置文件,我們使用了注解替代的映射文件,所以我們只需要加載使用了注解的Mapper接口即可
<mappers>
<!--掃描使用注解的類-->
<mapper class="com.yyl.mapper.UserMapper"></mapper>
</mappers>
? 或者指定掃描包含映射關(guān)系的接口所在的包也可以
<mappers>
<!--掃描使用注解的類所在的包-->
<package name="com.yyl.mapper"></package>
</mappers>

注解開發(fā)總結(jié)
注解可以簡化開發(fā)操作,省略映射配置文件的編寫。
常用注解
@Select(“查詢的 SQL 語句”):執(zhí)行查詢操作注解
@Insert(“查詢的 SQL 語句”):執(zhí)行新增操作注解
@Update(“查詢的 SQL 語句”):執(zhí)行修改操作注解
@Delete(“查詢的 SQL 語句”):執(zhí)行刪除操作注解
配置映射關(guān)系
<mappers>
<package name="接口所在包"/>
</mappers>
練習(xí)項目代碼
bean
package com.yyl.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 +
'}';
}
}mapper.class
package com.yyl.mapper;
import com.yyl.bean.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.List;
public interface StudentMapper {
//查詢?nèi)?
@Select("SELECT * FROM student")
public abstract List<Student> selectAll();
//新增操作
@Insert("INSERT INTO student VALUES (#{id},#{name},#{age})")
public abstract Integer insert(Student stu);
//修改操作
@Update("UPDATE student SET name=#{name},age=#{age} WHERE id=#{id}")
public abstract Integer update(Student stu);
//刪除操作
@Delete("DELETE FROM student WHERE id=#{id}")
public abstract Integer delete(Integer id);
}test
package com.yyl.test;
import com.yyl.bean.Student;
import com.yyl.mapper.StudentMapper;
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.獲取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);
}
//7.釋放資源
sqlSession.close();
is.close();
}
@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接口的實現(xiàn)類對象
StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
//5.調(diào)用實現(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();
}
@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接口的實現(xiàn)類對象
StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
//5.調(diào)用實現(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();
}
@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接口的實現(xiàn)類對象
StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
//5.調(diào)用實現(xiàn)類對象中的方法,接收結(jié)果
Integer result = mapper.delete(4);
//6.處理結(jié)果
System.out.println(result);
//7.釋放資源
sqlSession.close();
is.close();
}
}xml
<?xml version="1.0" encoding="UTF-8" ?>
<!--MyBatis的DTD約束-->
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<!--configuration 核心根標(biāo)簽-->
<configuration>
<!--引入數(shù)據(jù)庫連接的配置文件-->
<properties resource="jdbc.properties"/>
<!--配置LOG4J-->
<settings>
<setting name="logImpl" value="log4j"/>
</settings>
<!--起別名-->
<typeAliases>
<package name="com.yyl.bean"/>
</typeAliases>
<!--environments配置數(shù)據(jù)庫環(huán)境,環(huán)境可以有多個。default屬性指定使用的是哪個-->
<environments default="mysql">
<!--environment配置數(shù)據(jù)庫環(huán)境 id屬性唯一標(biāo)識-->
<environment id="mysql">
<!-- transactionManager事務(wù)管理。 type屬性,采用JDBC默認(rèn)的事務(wù)-->
<transactionManager type="JDBC"></transactionManager>
<!-- dataSource數(shù)據(jù)源信息 type屬性 連接池-->
<dataSource type="POOLED">
<!-- property獲取數(shù)據(jù)庫連接的配置信息 -->
<property name="driver" value="${driver}" />
<property name="url" value="${url}" />
<property name="username" value="${username}" />
<property name="password" value="${password}" />
</dataSource>
</environment>
</environments>
<!--配置映射關(guān)系-->
<mappers>
<package name="com.yyl.mapper"/>
</mappers>
</configuration>到此這篇關(guān)于Mybatis示例講解注解開發(fā)中的單表操作的文章就介紹到這了,更多相關(guān)Mybatis單表操作內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
關(guān)于Lambda表達(dá)式的方法引用和構(gòu)造器引用簡的單示例
這篇文章主要介紹了關(guān)于Lambda表達(dá)式的方法引用和構(gòu)造器引用簡的單示例,方法引用與構(gòu)造器引用可以使?Lambda?表達(dá)式的代碼塊更加簡潔<BR>,需要的朋友可以參考下2023-04-04
SpringBoot中對應(yīng)2.0.x版本的Redis配置詳解
這篇文章主要為大家介紹了SpringBoot中對應(yīng)2.0.x版本的Redis配置詳解,文中的實現(xiàn)步驟講解詳細(xì),感興趣的小伙伴們可以了解一下2022-06-06
Maven添加Tomcat插件實現(xiàn)熱部署代碼實例
這篇文章主要介紹了Maven添加Tomcat插件實現(xiàn)熱部署代碼實例,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-04-04

