You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot连接MS SQL遇多错误:登录失败及EntityManager缺失

问题解决方案

一、"用户'sav'登录失败"问题排查

  • 确认SQL Server用户权限:确保sav是SQL Server身份验证用户,拥有product12数据库的读写权限,用SSMS工具手动测试登录验证。
  • 检查连接字符串:若SQL Server修改过默认1433端口,需在spring.datasource.url中追加;port=xxxx;确保trustServerCertificate=true参数有效。
  • 验证数据库存在:确认product12数据库已在SQL Server中创建。

二、"EntityManager Bean无法找到"错误修复

1. 主类注解修正

主类存在路径错误、语法错误,修正后代码:

@SpringBootApplication
@EnableAdminServer
@EnableJpaRepositories(basePackages = "com.example.student.student.repository") // 替换为你的Repository实际所在包
public class AStudentApplication {

    // 若需注入EntityManager,使用@PersistenceContext而非@Autowired
    @PersistenceContext
    private EntityManager entityManager;

    public static void main(String[] args) {
        SpringApplication.run(AStudentApplication.class, args);
    }
}
  • 移除@ComponentScan:@SpringBootApplication默认扫描主类所在包及子包,无需额外配置。
  • @EnableJpaRepositories需指向Repository所在包,而非单个类。
  • 注入EntityManager必须用@PersistenceContext,它是JPA容器管理Bean的标准注入方式。

2. 补充Repository接口

必须创建继承JpaRepository的ProductRepo接口,示例:

package com.example.student.student.repository;

import com.example.student.student.model.Product;
import org.springframework.data.jpa.repository.JpaRepository;

public interface ProductRepo extends JpaRepository<Product, String> {
}

泛型第二个参数需与Product类的ID类型一致(你的代码中是String)。

3. Model类ID生成策略修正

GenerationType.IDENTITY仅适用于数值型自增主键,若坚持用String类型ID,修改为:

@Id
@GeneratedValue(strategy = GenerationType.UUID)
private String id;

或改为数值型ID更适配SQL Server自增机制:

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

4. Controller语法错误修复

createProduct方法缺少大括号,修正后:

@PostMapping("/Product")
public Product createProduct(@RequestBody Product product) {  
    return productrepo.save(product);    
}

5. 配置文件补充

取消Hibernate方言注释,确保SQL Server适配:

spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.SQLServer2012Dialect

三、验证流程

  1. 用SSMS验证sav用户登录product12数据库正常。
  2. 修正所有代码错误后启动项目,检查日志是否消除错误。

内容的提问来源于stack exchange,提问作者sourabh bisht

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 15:38:15