springboot使用druid 与 hibernate 插入utf8mb4编码的数据
时间: 2024-02-25 17:55:39 浏览: 40
要让Spring Boot使用Druid和Hibernate插入utf8mb4编码的数据,需要进行以下步骤:
1. 在pom.xml中添加Druid和Hibernate的依赖:
```
<!-- Druid -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>${druid.version}</version>
</dependency>
<!-- Hibernate -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
```
2. 修改application.properties或application.yml配置文件,添加Druid和Hibernate的配置:
```
# Druid
spring.datasource.druid.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai
spring.datasource.druid.username=root
spring.datasource.druid.password=root
spring.datasource.druid.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.druid.initial-size=5
spring.datasource.druid.min-idle=5
spring.datasource.druid.max-active=20
spring.datasource.druid.test-on-borrow=true
spring.datasource.druid.filters=stat,wall,slf4j
spring.datasource.druid.connection-properties=config.decrypt=false;config.decryptKey=MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAIgE8n5fJLrMw2Mn6v0RMy+Q7hL7Hr1T8WZa9zjx7z4fUfQwKvztz4jS7gj6hGz0n1t+HJFzjD6S2LZIlX0CAwEAAQ==
spring.datasource.druid.use-global-data-source-stat=true
# Hibernate
spring.jpa.database-platform=org.hibernate.dialect.MySQL5InnoDBUTF8mb4Dialect
spring.jpa.properties.hibernate.connection.CharSet=utf-8
spring.jpa.properties.hibernate.connection.useUnicode=true
spring.jpa.properties.hibernate.connection.characterEncoding=utf-8
spring.jpa.show-sql=true
```
3. 在实体类中添加@Column注解,指定数据库字段的字符集为utf8mb4:
```
@Entity
@Table(name = "user")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column(name = "name", columnDefinition = "varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci")
private String name;
// ...其他属性和方法
}
```
这样配置后,就可以使用Druid和Hibernate插入utf8mb4编码的数据了。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)