当前位置: 首页 > 知识库问答 >
问题:

Spring 启动Hibernate - 实体未映射配置的最佳方式

归和惬
2023-03-14

我正在尝试通过Hibernate学习 spring-boot 基本注释配置,使自己成为一个永远有效的模板。

我在STS(Spring工具套件)3.8.3上使用的是sping-引导最新版本1.51。

这是我的主要:

@SpringBootApplication
@EnableAutoConfiguration
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}

现在,我知道< code > @ spring boot application 自动附带< code>@componetScan,所以我没有添加它。

我的配置类:

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(entityManagerFactoryRef = "someEntityManagerFactory", transactionManagerRef = "someTransactionManager", basePackages = {
        "com.example.*" })
@EntityScan(basePackages = "com.demo.models")
@ConfigurationProperties(prefix = "mysql.datasource")
public class DataBaseConfig {

    @Autowired
    private Environment env;

    @Bean
    public DataSource someDataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName(env.getProperty("mysql.datasource.driver-class-name"));
        dataSource.setUrl(env.getProperty("mysql.datasource.url"));
        dataSource.setUsername(env.getProperty("mysql.datasource.username"));
        dataSource.setPassword(env.getProperty("mysql.datasource.password"));
        return dataSource;
    }

    @Bean
    public LocalContainerEntityManagerFactoryBean someEntityManagerFactory() {
        LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
        em.setDataSource(someDataSource());
        em.setPackagesToScan(new String[] { "org.openlegacy.analytics.models" });
        JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
        em.setJpaVendorAdapter(vendorAdapter);
        em.setJpaProperties(additionalProperties());

        return em;
    }

    @Bean
    public PlatformTransactionManager someTransactionManager() {
        JpaTransactionManager tm = new JpaTransactionManager();
        tm.setEntityManagerFactory(someEntityManagerFactory().getObject());
        tm.setDataSource(someDataSource());
        return tm;
    }

    Properties additionalProperties() {
        Properties properties = new Properties();
        properties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("spring.jpa.hibernate.ddl-auto"));
        properties.setProperty("hibernate.dialect", env.getProperty("spring.jpa.properties.hibernate.dialect"));
        properties.setProperty("spring.jpa.show-sql", env.getProperty("spring.jpa.show-sql"));
        properties.setProperty("spring.jpa.hibernate.naming.physical-strategy",
                env.getProperty("spring.jpa.hibernate.naming.physical-strategy"));
        return properties;
    }

}

我的控制器类:

@RestController
@RequestMapping("/users")
public class UserController {

    @Autowired
    private UserRepository userRipository;

    @RequestMapping(value = "", method = RequestMethod.GET)
    public List<User> getItems() {
        return userRipository.getUsers();
    }

    @RequestMapping(value = "/message", method = RequestMethod.GET)
    public String getMessage() {
        return userRipository.getMessage();
    }

}

我的存储库类:

@Transactional
@Repository
public class UserRepository {

    @PersistenceContext
    private EntityManager entityManager;

    @SuppressWarnings("unchecked")
    public List<User> getUsers() {
        return entityManager.createQuery("select u from User u").getResultList();
    }

    public String getMessage() {
        return "hello";
    }
}

我的实体类:

@Entity(name = "user")
public class User implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer id;

    @Column(name = "user_name")
    private String userName;

    @Column(name = "password")
    private String password;

    public Integer getId() {
        return id;
    }

    public void setId(Integer 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;
    }
}

和我的属性文件:

# DataSource settings: set here your own configurations for the database connection.
mysql.datasource.username=openlegacy
mysql.datasource.password=openlegacy
mysql.datasource.driver-class-name=com.mysql.jdbc.Driver
mysql.datasource.url=jdbc:mysql://localhost:3306/olbank
spring.jpa.database= MYSQL

spring.data.jpa.repositories.enabled=true
#spring.jpa.database-platform=org.hibernate.dialect.MYSQL5Dialect

# Show or not log for each sql query
spring.jpa.show-sql = true

# Hibernate ddl auto (create, create-drop, update)
spring.jpa.hibernate.ddl-auto = update

# Naming strategy
#spring.jpa.hibernate.naming.strategy= org.hibernate.cfg.ImprovedNamingStrategy
spring.jpa.hibernate.naming.physical-strategy= org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl

# The SQL dialect makes Hibernate generate better SQL for the chosen database
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect

当我绑定从用户表中检索数据时,我收到了这个错误:

org . hibernate . hql . internal . ast . query syntax exception:用户未映射...

我的问题是:

>

  • 为什么我会得到这个错误?我知道用户由类名映射,这就是我所做的

    这是用springboot配置hibernate的最佳方法吗?按照最佳实践编写代码对我来说很重要。

    请详细解答,我好借鉴

    欢迎提供任何其他有用的信息:)

    谢谢。

  • 共有3个答案

    端木令雪
    2023-03-14

    Spring JPA区分大小写,因此请确保您编写了确切的包URL和正确的类名。

    江阳夏
    2023-03-14

    如果您使用的是JPQL,那么不要忘记在存储库接口中的JPQL查询之后添加nativeQuery=true

    示例:-

    @Query(value="SELECT ID, NAME FROM USER", nativeQuery=true)
    Object getUser();
    
    上官景铄
    2023-03-14

    好的。您的整体配置中有一些需要解决的问题。您当前正在为您的实体用户提供别名

    @Entity(name = "user")
    

    这很好,但是如果您要为您的实体提供一个名称,那么这就是您需要在JPQL中引用它的方式,因此,“从用户u中选择u”需要变成

    select u from user u
    

    我可能只是建议去掉你的名字限定符,将你的查询保留为“从用户u中选择u”。

    其次,您在包引用方面确实存在一些问题:

    > < li >在您的< code > @ EnableJpaRepositories 批注中,将您的basePackages更改为引用实际存储库包的基础,猜测为< code > " com . demo . repository " 。去掉通配符引用。 < li>

    在someEntityManagerFactory()方法中,您将basePackage设置为(我认为这是不正确的)< code > " org . open legacy . analytics . models "。您指出您的实体位于< code >“com . demo . models”下。所以您应该将setter改为

    em.setPackagesToScan(new String[] { "com.demo.models" });
    

    这应该可以解决问题。

     类似资料:
    • 我在Kotlin-vertx项目中配置了Hibernate,我设法设置了所有内容,但当我运行HQL查询时,它会输出: 提前谢了。

    • 我想映射类主题到主题表。 主题。JAVA 主题。哈佛商学院。xml 冬眠cfg。xml 我正在读取csv文件的内容,并希望使用以下代码将其插入数据库。 管理ata.java 我得到以下错误 线程“main”组织中出现异常。冬眠MappingException:未知实体:组织中的主题。冬眠impl。SessionFactoryImpl。getEntityPersister(SessionFactor

    • 是否可以在不映射一对多关系的情况下设置级联? 我有两个实体: 和 如果我试图删除一个用户,并且存在该用户的任何记录,那么由于外键的原因,它显然会失败。我想在删除用户之前删除该用户的所有记录。我看到两种选择: > 映射s为关系中的,并设置。 在删除用户之前手动删除它们 有没有第三个选项,如何在用户实体中设置无映射记录的级联?

    • 我使用Hibernate已经有一段时间了,而且非常成功。然而,我昨天遇到了一个问题,这里的答案将在将来节省大量调试时间。 我忘了在我的hibernate中添加hibernate映射。新实体的cfg。 当我试图加载这个实体时,我本以为会得到某种运行时异常,但它却什么也没加载,继续运行,好像一切都很好。 我正在使用以下代码加载实体。 我想一个错误,如果我尝试加载一个实体,没有映射在我的hibernat

    • 在web应用程序上,我们使用Spring 3.2和Hibernate 4.1.1,并实现了一个类似插件的架构。插件可以在运行时添加和删除。对于每个模块,我们定义了一个单独的类加载器,并在spring上创建了单独的子应用程序上下文。完整的配置是使用注释完成的,不再需要对beans进行XML配置。 Spring Hibernate配置类 现在的问题是:一些插件包含自己的实体(DAO)类,这些类在运行时

    • 我目前正在尝试使用ModelMapper的映射方法执行实体到DTO的映射。在最深的属性映射上,映射结果为null,但它应该是一个对象。 以下是我的映射源实体(省略brevety的Loombok getter和setter): 以下是我的目标DTO(省略brevety的Loombok Getter和Setter): 在我的Controller类方法上,我这样做映射: My clientService