Spring boot + Hibernate + MySQL实现用户管理示例
安装MySQL
Windows 11 Mysql 安装及常用命令_windows11 mysql-CSDN博客
整体目录
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.4.0</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.test</groupId>
<version>0.0.1-SNAPSHOT</version>
<artifactId>mservice-sql</artifactId>
<name>mservice-sql</name>
<description>mservice-sql</description>
<url/>
<licenses>
<license/>
</licenses>
<developers>
<developer/>
</developers>
<scm>
<connection/>
<developerConnection/>
<tag/>
<url/>
</scm>
<properties>
<java.version>21</java.version>
<spring-cloud.version>2024.0.0</spring-cloud.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
application.properties
配置端口号和MySQL连接
server.port=8000
#数据库连接
spring.datasource.primary.jdbc-url=jdbc:mysql://localhost:3306/数据库名
#数据库用户名
spring.datasource.primary.username=用户名
#数据库密码
spring.datasource.primary.password=密码
#自动更新数据库
spring.jpa.properties.hibernate.hbm2ddl.auto=update
#显示sql
spring.jpa.show-sql=true
#在视图渲染过程中不执行数据库查询
spring.jpa.open-in-view=false
SqlApplication.java
package com.test;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SqlApplication {
public static void main(String[] args) {
SpringApplication.run(SqlApplication.class, args);
}
}
User.java
注意:import jakarta.persistence.*;
package com.test.entity;
import java.io.Serializable;
import jakarta.persistence.*;
@Entity
@Table(name = "users")
public class User implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String username;
private String password;
// Getters and Setters
public Long getId() {
return id;
}
public void setId(Long 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;
}
}
UserRepository
package com.test.dao;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.repository.NoRepositoryBean;
import org.springframework.stereotype.Repository;
import com.test.entity.User;
public interface UserRepository {
User findById(Long id);
User save(String username,String password);
}
UserDao
注解@PersistenceContext(unitName = "primaryEntityManager")须与PrimaryDbConfig中一致。
package com.test.dao;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.springframework.stereotype.Repository;
import com.test.entity.User;
import jakarta.persistence.EntityManager;
import jakarta.persistence.PersistenceContext;
@Repository
public class UserDao implements UserRepository{
@PersistenceContext(unitName = "primaryEntityManager")
private EntityManager entityManager;
@Override
public User findById( Long id) {
try {
User user = entityManager.find(User.class, id);
return user;
}catch(HibernateException e) {
e.printStackTrace();
}
return null;
}
@Override
public User save(String username,String password) {
User user = new User();
user.setUsername(username);
user.setPassword(password);
try {
entityManager.persist(user);
return user;
}catch(HibernateException e) {
e.printStackTrace();
}
return user;
}
}
PrimaryDbConfig
其中:"com.test.dao"是Dao路径;"com.test.entity"是实体路径。
package com.test.conf;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import javax.sql.DataSource;
/*
*
* 数据库配置
*
* basePackages:JPA扫描配置
* entityManagerFactoryRef:实体扫描配置
* transactionManagerRef:事务配置
*
* */
@Configuration
@EnableJpaRepositories(basePackages = "com.test.dao", entityManagerFactoryRef = "primaryEntityManager", transactionManagerRef = "primaryTransactionManager")
public class PrimaryDbConfig {
private final Logger log = LoggerFactory.getLogger(getClass());
private DataSource dataSource;
private LocalContainerEntityManagerFactoryBean entityManager;
/*
* 创建数据库连接
* @Primary 配置多个数据源时,用于标记主库
* @ConfigurationProperties 指定配置文件中的属性前缀
*
* */
@Primary
@ConfigurationProperties(prefix = "spring.datasource.primary")
@Bean(name = "primaryDataSource")
public DataSource primaryDataSource() {
dataSource = DataSourceBuilder.create().build();
log.info("正在连接数据库1...");
return dataSource;
}
/*
* 实体扫描配置
*
* 方法名与类注解中的entityManagerFactoryRef的值保持一致,配置多个数据源时方法名不能相同
*
* */
@Bean
@Primary
LocalContainerEntityManagerFactoryBean primaryEntityManager(EntityManagerFactoryBuilder builder) {
log.info("正在扫描接数据库1的实体类...");
entityManager = builder.dataSource(dataSource).packages("com.test.entity")
.persistenceUnit("primaryPersistenceUnit").build();
return entityManager;
}
/*
* 事务配置
*
* 方法名与类注解中的transactionManagerRef的值保持一致,配置多个数据源时方法名不能相同
*
* */
@Bean
@Primary
PlatformTransactionManager primaryTransactionManager(EntityManagerFactoryBuilder builder) {
log.info("正在配置接数据库1的事务管理器...");
return new JpaTransactionManager(entityManager.getObject());
}
}
UserController:
注意:save接口的注解@Transactional(value = "primaryTransactionManager")
package com.test.controller;
import com.test.entity.User;
import com.test.dao.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
@Controller
@RequestMapping("/api/users")
public class UserController {
@Autowired
private UserRepository userService;
@RequestMapping("/id")
@ResponseBody
public User getUserById( Long id) {
return userService.findById(id);
}
@RequestMapping("/save")
@ResponseBody
@Transactional(value = "primaryTransactionManager")
public User save(String name,String password) {
return userService.save(name, password);
}
}
启动程序:
此时数据库中自动创建了数据表users。
浏览器测试:
添加用户:
http://localhost:8000/api/users/save?name=test&password=12345
查询用户:
http://localhost:8000/api/users/id?id=1
Navicat查看MySQL: