当前位置: 首页 > article >正文

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:


http://www.kler.cn/a/460272.html

相关文章:

  • 【数据库系列】Spring Boot 中整合 MyBatis-Plus详细步骤
  • 2000-2020年各省财政一般预算支出面板数据
  • Kraft模式安装Kafka(含常规、容器两种安装方式)
  • 怎样在 Word 文档中插入附件(其他文件)?
  • 一文理解条件竞争漏洞
  • win10、win11-鼠标右键还原、暂停更新
  • logback之自定义过滤器
  • 【AndroidAPP】权限被拒绝:[android.permission.READ_EXTERNAL_STORAGE],USB设备访问权限系统报错
  • C语言一维数组与指针运算
  • 《计算机组成及汇编语言原理》阅读笔记:p133-p159
  • WPF的下拉复选框多选,数据来源数据库的表
  • 【人工智能机器学习基础篇】——深入详解深度学习之神经网络基础:理解前馈神经网络与反向传播算法
  • 医疗数仓配置Flume
  • 使用maven-mvnd替换maven大大提升编译打包速度
  • sublime 文件高亮设置
  • vim编辑器实用设置
  • VirtualBox新版本报错 Invalid installation directory解决方案
  • C#封送类
  • Tesseract-OCR 文字识别
  • 【Spring】Spring DI(依赖注入)详解—自动装配—byType实现原理
  • 智元与汇川加码,机器人如何利好电机市场?
  • Sigrity System SI SerialLink模式进行HDMI2协议仿真分析操作指导-TP1
  • AI安全的挑战:如何让人工智能变得更加可信
  • 【从零开始入门unity游戏开发之——C#篇41】C#迭代器(Iterator)——自定义类实现 foreach 操作
  • 图像处理-Ch7-小波函数
  • 开源大数据平台E-MapReduce