Spring Boot与MySQL交互
2026/5/30 17:52:59 网站建设 项目流程

Spring Boot与MySQL交互的核心步骤

配置MySQL依赖与数据源
pom.xml中添加依赖:

<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-jpa</artifactId></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId></dependency>

application.properties中配置数据源:

spring.datasource.url=jdbc:mysql://localhost:3306/数据库名?useSSL=false&serverTimezone=UTC spring.datasource.username=用户名 spring.datasource.password=密码 spring.jpa.hibernate.ddl-auto=update

实体类映射数据库表
使用JPA注解定义实体类:

@Entity@Table(name="user")publicclassUser{@Id@GeneratedValue(strategy=GenerationType.IDENTITY)privateLongid;@Column(nullable=false)privateStringname;// getters/setters省略}

创建Repository接口
继承JpaRepository实现CRUD操作:

publicinterfaceUserRepositoryextendsJpaRepository<User,Long>{List<User>findByName(Stringname);}

服务层调用Repository

@ServicepublicclassUserService{@AutowiredprivateUserRepositoryuserRepository;publicUsersaveUser(Useruser){returnuserRepository.save(user);}}

事务管理
在服务层方法添加事务注解:

@TransactionalpublicvoidupdateUser(Useruser){userRepository.save(user);}

高级交互技巧

自定义SQL查询
在Repository中使用@Query注解:

@Query("SELECT u FROM User u WHERE u.name LIKE %:keyword%")List<User>searchByKeyword(@Param("keyword")Stringkeyword);

分页与排序
通过Pageable参数实现:

Page<User>findAll(Pageablepageable);

多数据源配置
需单独配置多个DataSource和EntityManager:

@Configuration@EnableJpaRepositories(basePackages="com.primary.repository",entityManagerFactoryRef="primaryEntityManager")publicclassPrimaryDataSourceConfig{// 详细配置省略}

性能优化建议
启用JDBC批处理:

spring.jpa.properties.hibernate.jdbc.batch_size=20 spring.jpa.properties.hibernate.order_inserts=true

连接池配置
推荐使用HikariCP:

spring.datasource.hikari.maximum-pool-size=10 spring.datasource.hikari.connection-timeout=30000

异常处理方案

数据校验
在实体类字段添加校验注解:

@NotBlank@Size(max=100)privateStringname;

统一异常处理
使用@ControllerAdvice捕获数据库异常:

@ExceptionHandler(DataIntegrityViolationException.class)publicResponseEntity<String>handleConstraintViolation(){returnResponseEntity.badRequest().body("数据约束冲突");}

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询