Spring boot+hibernate-实体未映射+最佳配置方式
我正试图通过hibernate学习SpringBoot的基本注释配置,使自己成为一个始终有效的模板 我在STS spring工具套件3.8.3上使用spring boot最新版本1.51 以下是我的主要观点:Spring boot+hibernate-实体未映射+最佳配置方式,hibernate,spring-boot,Hibernate,Spring Boot,我正试图通过hibernate学习SpringBoot的基本注释配置,使自己成为一个始终有效的模板 我在STS spring工具套件3.8.3上使用spring boot最新版本1.51 以下是我的主要观点: @SpringBootApplication @EnableAutoConfiguration public class DemoApplication { public static void main(String[] args) { SpringApplic
@SpringBootApplication
@EnableAutoConfiguration
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
现在,我知道@SpringBootApplication自动附带@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();
}
}
和我的属性文件:
# 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.QuerySyntaxException:未映射用户
我的问题是:
为什么我会犯这个错误?我知道用户是通过类名映射的,这就是我正在做的
这是用spring boot配置hibernate的最佳方法吗?根据最佳实践编写代码对我来说很重要
请给出一个详细的答案,以便我能从中学习
欢迎提供任何其他有用的信息:
谢谢。好的。您需要在总体配置中解决一些问题。您当前正在为实体用户提供别名
@Entity(name = "user")
这很好,但如果您要为您的实体提供一个名称,那么这就是您需要在JPQL中引用它的方式,因此,从用户u中选择u将需要成为
select u from user u
我可能只是建议去掉您的名称限定符,将查询保留为select u from User u
其次,您在包引用方面确实存在一些问题:
在@EnableJpaRepositories注释中更改基本包
要引用实际存储库包的基础,请猜测
com.demo.repository。去掉通配符引用。
在someEntityManagerFactory方法中,您正在设置
basePackage与我想象中的东西不符
org.openlegacy.analytics.models。你说你的实体是
在com.demo.models下。所以你应该把那个setter改成
em.setPackagesToScan(new String[] { "com.demo.models" });
这应该可以做到。Spring JPA区分大小写,因此请确保您编写了准确的包URL和正确的类名。实体未映射到JPA本机查询 使用SpringBootJPA,默认情况下,每个查询将引用在@Entity类中定义的列或变量,该类映射到数据库中的每个列 但是,可以使用本机查询或原始查询
public interface UserInfoRepository extends CrudRepository<UserModel, String>
@Query("SELECT ID, NAME FROM USER", nativeQuery = true)
Optional<List<UserModel>> findSomething();
}
我对配置Oracle的最佳方法的建议
在application.yml中配置数据源
使用lombok或不使用lombok手动创建@Entity类创建getter、setter函数
创建接口CRUD存储库
最后,在控制器中调用@Service类
希望,这是几周前像我这样有麻烦的人的指南你有没有试着为实体吼叫:
@Entity
@Table(name = "user")
public class User implements Serializable {
}
在我的例子中,我必须为实体添加名称。 @Entityname=用户 更新 如果您将实体保留为没有名称,并写入类名,那么它也应该可以工作
@Entity
@Table
public class User implements Serializable{
}
然后
@query("select u from User u")
@EntityScan注释表示basePackages=com.demo.models。你的用户实体真的在那个包中吗?是的,它在com.demo.models包中-@M.RizzoGreat。您的DemoApplication在哪个软件包中?我的DemoApplication在com.demo package@M.Rizzo中
spring:
datasource:
type: com.zaxxer.hikari.HikariDataSource
username: username
password: pass
hikari:
idle-timeout: 1000
maximum-pool-size: 10
minimum-idle: 2
pool-name: pool-name
jdbc-url: jdbc:oracle:thin:@localhost:1521:INSTANCE
driver-class-name: oracle.jdbc.OracleDriver
@Data
@NoArgsConstructor
@EntityScan
@Entity(name = "USER")
public class UserInfoModel {
@Id
@Column(name = "USERID")
private long userId;
@Column(name = "NAME")
private String name;
@Column(name = "DEPT")
private String dept;
}
public interface UserInfoRepository extends CrudRepository<UserInfoModel, Long> {
}
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserInfoRepository userInfoRepo;
@Override
public List<UserInfoModel> getUserInfo(long userId) throws Exception {
Optional<List<UserInfoModel>> info = userInfoRepo.findById(userId);
if (!info.isEmpty() && info.get().size() > 0) {
return info.get();
}
return null;
}
}
@RestController
@RequestMapping("/webint")
public class UserController {
@Autowired
private UserService userService;
}
@Entity
@Table(name = "user")
public class User implements Serializable {
}
@Entity(name = "users")
@Table(name = "users")
public class User implements Serializable{
}
@Entity
@Table
public class User implements Serializable{
}
@query("select u from User u")