Spring Mybatis 基本使用過程(推薦)
1. 簡介
Mybatis庫可以簡化數(shù)據(jù)庫的操作,專注于sql語句。
2.搭建步驟
2.1 在pom.xml引入mybatis
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.11</version>
</dependency>2.2 在resources下新建mybatis配置文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Mapper 3.0/EN"
"https://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<settings>
<!-- <setting name="logImpl" value="STDOUT_LOGGING"/><!– 開啟mybatis的日志輸出 –>-->
<setting name="mapUnderscoreToCamelCase" value="true"/><!-- 開啟駝峰式自動映射 a_big => aBig -->
</settings>
<typeAliases>
<typeAlias alias="goods" type="com.jojo.pojo.Goods"/><!-- 單獨設置別名 -->
<package name="com.jojo.pojo"/><!-- 批量設置別名, com.jojo.pojo包下的所有類名的別名為類的首字母小寫-->
</typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/> <!-- 自動開啟事務 -->
<dataSource type="POOLED"><!-- mybatis維護連接池 -->
<property name="driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis-example"/>
<property name="username" value="root"/>
<property name="password" value="a12345678"/>
</dataSource>
</environment>
</environments>
<mappers>
<!-- 指定mapper xml文件的位置 -->
<mapper resource="mappers/GoodsMapper.xml"/>
</mappers>
</configuration>2.3 在resources/mapper下新建mapper的xml配置文件:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0/EN"
"https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.jojo.mapper.GoodsMapper"><!-- 對應Mapper的全限定符 -->
<!-- 這里寫sql語句 -->
<insert id="insert" useGeneratedKeys="true" keyColumn="id" keyProperty="id">
insert into goods (name) value(#{name})
</insert>
<update id="update">
update goods set name=#{name} where id=#{id}
</update>
<delete id="delete">
delete from goods where id = #{id}
</delete>
<select id="selectById" resultType="goods">
select * from goods where id = #{id}
</select>
<select id="selectAll" resultType="goods">
select * from goods
</select>
</mapper>2.4 新建pojo類
import lombok.Data;
@Data//lombook插件的@Data標簽可以自動生成get和set以及toString方法
public class Goods {
private Integer id;
private String name;
}2.5 新建mapper接口
public interface GoodsMapper {
int insert(Goods goods);
int update(Goods goods);
int delete(Integer id);
Goods selectById(Integer id);
List<Goods> selectAll();
}2.6 測試
public class MybatisTest {
@Test
public void test() throws IOException {
//1.讀取外部配置文件
InputStream ips = Resources.getResourceAsStream("mybatis-config.xml");
//2.創(chuàng)建sqlSessionFactory
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(ips);
//3.根據(jù)sqlSessionFactory創(chuàng)建sqlSession
SqlSession sqlSession = sqlSessionFactory.openSession();
//4.獲取接口的代理對象,調(diào)用代理對象的方法就會查找mapper接口的方法
GoosdMapper mapper = sqlSession.getMapper(GoosdMapper.class);
Goods goods = mapper.queryById(1);
System.out.println(goods);
//5.提交事務和釋放資源
//sqlSession.commit();
sqlSession.close();
}
}3.常用mapper語句
3.1 傳入值
<!-- #{id} = 使用占位符?,防止sql注入攻擊,但不能替代表名表項-->
<!-- ${id} = 不使用占位符?,不能防止sql注入攻擊,但可以替代表名表項-->
<select id="queryById" resultType="com.jojo.pojo.Employee">
select emp_id empId,emp_name empName, emp_salary empSalary from t_emp where emp_id = #{id}
</select>
<delete id="deleteById">
delete from t_emp where emp_id = #{id} <!-- 傳入Integer類型,id可以改寫成任意字符串-->
</delete>
<select id="queryBySalary" resultType="com.jojo.pojo.Employee">
select emp_id empId,emp_name empName, emp_salary empSalary from t_emp where empSalary = #{salary} <!-- 傳入Double類型,salary可以改寫成任意字符串-->
</select>
<insert id="insertEmp">
insert into t_emp (emp_name, emp_salary) values (#{empName},#{empSalary});<!-- 傳入對象時,要寫傳入對象的屬性 -->
</insert>
<select id="queryByNameAndSalary" resultType="com.jojo.pojo.Employee">
select emp_id empId,emp_name empName, emp_salary empSalary from t_emp where empSalary = #{a} and empName = # <!-- 傳入兩個基本類型,根據(jù)接口中的@Param("名稱")來指定-->
</select>
<select id="queryByNameAndSalary" resultType="com.jojo.pojo.Employee">
select emp_id empId,emp_name empName, emp_salary empSalary from t_emp where empSalary = #{arg0} and empName = #{arg1} <!-- 法2:傳入兩個基本類型,可以根據(jù)順序來取arg0...arg1...-->
</select>
<select id="queryByNameAndSalary" resultType="com.jojo.pojo.Employee">
select emp_id empId,emp_name empName, emp_salary empSalary from t_emp where empSalary = #{param1} and empName = #{param2} <!-- 法3:傳入兩個基本類型,可以根據(jù)順序來取param1...param2...-->
</select>
<insert id="insertEmpMap">
insert into t_emp (emp_name, emp_salary) values (#{name},#{salary});<!-- 傳入Map時,要寫傳入Map的key -->
</insert>3.2 返回值
<select id="queryNameById" resultType="string"><!-- resultType指定返回的類型,寫類的全限定符或者mybatis提供的別名(在mybatis官網(wǎng)查)-->
select emp_name from t_emp where emp_id = #{id}
</select>
<select id="queryById" resultType="employee"> <!-- resultType指定返回的為對象時,select的行需要起別名來與類的屬性完全一致-->
select emp_id empId,emp_name empName, emp_salary empSalary from t_emp where emp_id = #{id}
</select>
<select id="queryById" resultType="employee"><!-- resultType指定返回的為對象時,開啟駝峰映射(mapUnderscoreToCamelCase)后,select的行不再需要起別名來與類的屬性完全一致-->
select * from t_emp where emp_id = #{id}
</select>
<select id="selectEmpNameAndMaxSalary" resultType="map"> <!-- resultType返回的值沒有未定義類時,可以用map接值,map的每一項的key對應一個列名 -->
select emp_name 員工姓名, emp_salary 員工工資, (SELECT AVG(emp_salary) from t_emp) 部門平均工資 from t_emp where emp_salary=(select max(emp_salary) from t_emp)
</select>
<select id="queryNamesBySalary" resultType="string"><!--如果返回類型時List<String>,那么指定String即可-->
select emp_name from t_emp where emp_salary > #{ salary};
</select>
<select id="queryAll" resultType="employee"><!--如果返回類型時List<Employee>,那么指定Employee即可-->
select * from t_emp;
</select>
<insert id="insertEmp" useGeneratedKeys="true" keyColumn="emp_id" keyProperty="empId"><!-- 主鍵自增長型:插入時,獲取插入的id放在empId中 -->
insert into t_emp (emp_name, emp_salary) value(#{empName},#{empSalary});
</insert>
<insert id="insertTeacher">
<selectKey order="BEFORE" resultType="string" keyProperty="tId">
select replace(UUID(),'-',''); <!-- 插入前由數(shù)據(jù)庫生成uuid并放在tId中-->
</selectKey>
insert into teacher (t_id,t_name) value (#{tId},#{tName})
</insert>4.多表查詢
4.1 一對一
1對1關系:一個A類中包含一個B類:
public class A {
private Integer Id;
private String aName;
private Integer bId;
private B b;
}
public class B {
private Integer bId;
private String bName;
}使用resultMap來裝數(shù)據(jù):
<resultMap id="aMap" type="a">
<!-- a的主鍵 id標簽-->
<id column="a_id" property="aId"/>
<!-- order的普通列 custom標簽-->
<result column="a_name" property="aName"/>
<result column="b_id" property="bId"/>
<!-- 給第二層對象屬性賦值 -->
<association property="b" javaType="b">
<id column="b_id" property="bId"/>
<result column="b_name" property="bName"></result>
</association>
</resultMap>
<select id="queryAById" resultMap="aMap">
SELECT * FROM t_a ta join t_b tb on ta.b_id = tb.b_id where ta.a_id = #{id};
</select>在config文件中加入:
<settings>
<!-- 開啟駝峰式自動映射 a_big => aBig -->
<setting name="mapUnderscoreToCamelCase" value="true"/>
<!-- 開啟自動映射 a_big => aBig -->
<setting name="autoMappingBehavior" value="FULL"/>
</settings>后可省略主鍵以外的映射關系:
<resultMap id="aMap" type="a">
<!-- a的主鍵 id標簽-->
<id column="a_id" property="aId"/>
<!-- 給第二層對象屬性賦值 -->
<association property="b" javaType="b">
<id column="b_id" property="bId"/>
</association>
</resultMap>
<select id="queryAById" resultMap="aMap">
SELECT * FROM t_a ta join t_b tb on ta.b_id = tb.b_id where ta.a_id = #{id};
</select>4.2 一對多
1對多關系:一個A類中包含多個B類(List):
public class A {
private Integer Id;
private String aName;
private Integer bId;
private List<B> bList;
}
public class B {
private Integer bId;
private String bName;
}使用resultMap來裝數(shù)據(jù):
<resultMap id="aMap" type="a">
<id column="a_id" property="aId"/>
<result column="a_name" property="aName"/>
<result column="b_id" property="bId"/>
<!--針對List<A>屬性使用collection -->
<collection property="bList" ofType="b">
<id column="b_id" property="bId"></id>
<result column="b_name" property="bName"/>
</collection>
</resultMap>
<select id="queryAList" resultMap="aMap">
select * from t_a ta join t_b tb on ta.customer_id = tb.customer_id
</select>在config文件中加入:
<settings>
<!-- 開啟駝峰式自動映射 a_big => aBig -->
<setting name="mapUnderscoreToCamelCase" value="true"/>
<!-- 開啟自動映射 a_big => aBig -->
<setting name="autoMappingBehavior" value="FULL"/>
</settings>后可省略主鍵以外的映射關系:
<resultMap id="aMap" type="a">
<id column="a_id" property="aId"/>
<!--針對List<A>屬性使用collection -->
<collection property="bList" ofType="b">
<id column="b_id" property="bId"></id>
</collection>
</resultMap>
<select id="queryAList" resultMap="aMap">
select * from t_a ta join t_b tb on ta.customer_id = tb.customer_id
</select>到此這篇關于Spring Mybatis 基本使用 總結的文章就介紹到這了,更多相關Spring Mybatis 使用內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Spring如何通過注解引入外部資源(PropertySource?Value)
這篇文章主要為大家介紹了Spring通過注解@PropertySource和@Value引入外部資源的方法實現(xiàn)示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-07-07
Java將網(wǎng)絡圖片轉(zhuǎn)成輸入流以及將url轉(zhuǎn)成InputStream問題
這篇文章主要介紹了Java將網(wǎng)絡圖片轉(zhuǎn)成輸入流以及將url轉(zhuǎn)成InputStream問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-01-01
spring?bean標簽中的init-method和destroy-method詳解
這篇文章主要介紹了spring?bean標簽中的init-method和destroy-method,在很多項目中,經(jīng)常在xml配置文件中看到init-method 或者 destroy-method ,因此整理收集下,方便以后參考和學習,需要的朋友可以參考下2023-04-04

