SpringBoot常用數(shù)據(jù)庫開發(fā)技術(shù)匯總介紹
1.概述
數(shù)據(jù)庫開發(fā)一直是JAVA開發(fā)的核心之一,作為現(xiàn)在JAVA EE的基石框架,Spring Boot自身攜帶了一個JDBCTemplate框架,其對JDBC進(jìn)行了基礎(chǔ)的封裝,使得Spring Boot原生就支持據(jù)庫開發(fā)。同時Spring Boot也不排斥其它優(yōu)秀的持久層框架,允許他們以極低的代價平滑的接入。
本文主要介紹最常用到的三個持久層框架,JdbcTemplate、JPA、mybatis如何接入Spring Boot并在其上進(jìn)行開發(fā)。
2.環(huán)境
- spring boot 2.6.3
- MySQL
基礎(chǔ)依賴:
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!--mysql驅(qū)動--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> </dependencies> <dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-dependencies</artifactId> <version>2.6.3</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement>
表:
CREATE TABLE `user` ( id int NOT NULL AUTO_INCREMENT, username varchar(50) NOT NULL, password varchar(50) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
數(shù)據(jù)庫配置:
# 數(shù)據(jù)庫連接配置
spring.datasource.url=jdbc:mysql://localhost:3306/mydb?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=GMT%2B8
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
3.JdbcTemplate
JdbcTemplate是spring框架里面提供的一個JDBC的抽象層,封裝了對創(chuàng)建的SQL操作,如SQL語句執(zhí)行、結(jié)果處理等功能,使得我們能更方便地使用JDBC。
依賴:
JdbcTemplate是spring框架里的東西,在Spring Boot體系里其被包含在jdbc的starter中。
<!--jdbc依賴,包含jdbcTemplate--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency>
使用:
@Service public class UserService { @Autowired JdbcTemplate jdbcTemplate; RowMapper<User> userMapper=new RowMapper<User>() { public User mapRow(ResultSet resultSet, int rowNum) throws SQLException { User user = new User(); user.setId(resultSet.getInt("id")); user.setUsername(resultSet.getString("username")); user.setPassword(resultSet.getString("password")); return user; } }; // 插入一條用戶數(shù)據(jù) public void addUser(User user) { String sql = "INSERT INTO user (username, password) VALUES (?, ?)"; jdbcTemplate.update(sql, user.getUsername(), user.getPassword()); } // 刪除一條用戶數(shù)據(jù) public void deleteUser(int id) { String sql = "DELETE FROM user WHERE id = ?"; jdbcTemplate.update(sql, id); } // 更新一條用戶數(shù)據(jù) public void updateUser(User user) { String sql = "UPDATE user SET username = ?, password = ? WHERE id = ?"; jdbcTemplate.update(sql, user.getUsername(), user.getPassword(), user.getId()); } // 查詢所有用戶數(shù)據(jù) public List<User> findAllUsers() { String sql = "SELECT id, username, password FROM user"; return jdbcTemplate.query(sql, userMapper); } // 根據(jù) ID 查詢一條用戶數(shù)據(jù) public User findUserById(int id) { String sql = "SELECT id, username, password FROM user WHERE id = ?"; return jdbcTemplate.queryForObject(sql, new Object[]{id}, userMapper); } }
4.JPA
4.1.概述
JPA(Java persistence api,JAVA持久化API),是一種JSR規(guī)范,其定義了Java對象和關(guān)系型數(shù)據(jù)庫之間該如何映射,總結(jié)起來是:
- 對象關(guān)系映射,需要描述好對象中的每個屬性和關(guān)系型數(shù)據(jù)中每個字段之間的映射關(guān)系。
- 操作API,需要提供一套基礎(chǔ)CRUD的API。
- 查詢語言,需要支持自定義SQL進(jìn)行比較靈活的查詢。
spring boot中對jpa的實現(xiàn)是基于hibernate的,其通過注解來實現(xiàn)對象關(guān)系映射、提供了一套基礎(chǔ)CRUD的API,然后依托于HQL支持了自定義SQL進(jìn)行靈活的查詢。
4.2.基本使用
依賴:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency>
對象關(guān)系映射:
@Entity(name="user") @Table(name = "user") public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int id; @Column(name = "username") private String username; @Column(name="password") private String password; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
接口:
這是spring boot jpa的關(guān)鍵,接口繼承JpaRepository,定義好實體關(guān)系映射和id類型。
import com.eryi.bean.User; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Service; @Service public interface UserService extends JpaRepository<User,Integer> { }
使用:
JpaRepository自帶了一套基礎(chǔ)CRUD的API,直接調(diào)用即可。
@RequestMapping("getUser") public User addUser(User user){ return userService.findById(user.getId()).get(); }
4.3.轉(zhuǎn)換器
有時候數(shù)據(jù)庫里存的字段值不是我們直接想要的,而是需要做一些轉(zhuǎn)換,比如user如果有個性別字段,數(shù)據(jù)庫里可能是用1表示男性,用2表示女性,而我們想要的是男女,Spring Boot Jpa提供了轉(zhuǎn)換器來進(jìn)行轉(zhuǎn)換。
定義轉(zhuǎn)換器:
public class SexConverter implements AttributeConverter<SexEnum,Integer>{ //將枚舉轉(zhuǎn)換為數(shù)據(jù)庫列 @Override public Integer convertToDatabaseColumn (SexEnum sex) { return sex.getId () ; //將數(shù)據(jù)庫列轉(zhuǎn)換為枚 @Override publ ic SexEnum convertToEntityAttrbute (Integer id) { return SexEnum.getEnumByid (id); }
在想要進(jìn)行轉(zhuǎn)換的字段上使用轉(zhuǎn)換器:
public class User{ @Convert(converter=SexConverter.class) private SexEnum sex; }
5.mybatis
mybatis就不贅述了,現(xiàn)在大家最常用的,直接開整!
依賴:
<dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.7</version> </dependency>
配置:
# 數(shù)據(jù)庫連接配置
spring.datasource.url=jdbc:mysql://localhost:3306/mydb?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=GMT%2B8
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
# MyBatis 配置
# 說明mapper的xml文件在哪里
mybatis.mapper-locations=classpath:mapper/*.xml
實體類:
public class User { private Long id; private String username; private String password; // getter 和 setter 方法省略 }
接口:
@Mapper public interface UserDao { User getUserById(Long id); List<User> getAllUsers(); void addUser(User user); void updateUser(User user); void deleteUser(Long id); }
mapper.xml:
在 src/main/resources/mapper`目錄下創(chuàng)建 UserDao.xml 文件。
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.example.demo.dao.UserDao"> <select id="getUserById" parameterType="long" resultType="com.example.demo.entity.User"> SELECT * FROM user WHERE id = #{id} </select> <select id="getAllUsers" resultType="com.example.demo.entity.User"> SELECT * FROM user </select> <insert id="addUser" parameterType="com.example.demo.entity.User"> INSERT INTO user (username, password) VALUES (#{username}, #{password}) </insert> <update id="updateUser" parameterType="com.example.demo.entity.User"> UPDATE user SET username = #{username}, password = #{password} WHERE id = #{id} </update> <delete id="deleteUser" parameterType="long"> DELETE FROM user WHERE id = #{id} </delete> </mapper>
到此這篇關(guān)于SpringBoot常用數(shù)據(jù)庫開發(fā)技術(shù)匯總介紹的文章就介紹到這了,更多相關(guān)SpringBoot數(shù)據(jù)庫開發(fā)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Java中HashMap和Hashtable的區(qū)別小結(jié)
本文主要介紹了Java中HashMap和Hashtable的區(qū)別小結(jié),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-07-07Spring Cloud微服務(wù)架構(gòu)的構(gòu)建:分布式配置中心(加密解密功能)
這篇文章主要給大家介紹了關(guān)于Spring Cloud微服務(wù)架構(gòu)的構(gòu)建:分布式配置中心(加密解密)的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家學(xué)習(xí)或者使用具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2018-05-05Springboot中如何使用過濾器校驗PSOT類型請求參數(shù)內(nèi)容
在Springboot中創(chuàng)建過濾器,用來過濾所有POST類型請求并獲取body中的參數(shù)進(jìn)行校驗內(nèi)容是否合法,該方法僅適用于POST類型請求,本文給大家介紹Springboot中如何使用過濾器校驗PSOT類型請求參數(shù)內(nèi)容,感興趣的朋友一起看看吧2023-08-08基于logback 實現(xiàn)springboot超級詳細(xì)的日志配置
java web 下有好幾種日志框架,比如:logback,log4j,log4j2(slj4f 并不是一種日志框架,它相當(dāng)于定義了規(guī)范,實現(xiàn)了這個規(guī)范的日志框架就能夠用 slj4f 調(diào)用)。這篇文章主要介紹了基于logback springboot超級詳細(xì)的日志配置,需要的朋友可以參考下2019-06-06