java-没有jpa的Spring和Hibernate
作者:互联网
对于我的新项目,我计划使用Hibernate 5和Spring 4,并且一如既往地希望分成不同的层/项目.
Gradle依赖项:
"org.springframework:spring-webmvc:4.2.1.RELEASE",
"org.springframework:spring-orm:4.2.1.RELEASE",
'org.hibernate:hibernate-core:5.0.2.Final',
'mysql:mysql-connector-java:5.1.36'
有一个API项目,其中包含User.class.我认为该用户类不得对数据库层使用任何注释.它不能指定@Table(name =“ users”)或其他内容.它应该是带有getter和setter的简单对象.
数据库层应决定如何存储数据,这在很大程度上取决于数据库(例如MongoDB或MySQL).
我遵循了一些有关Hibernate的教程,最后得到了以下@Configuration类
@Configuration
@ComponentScan("de.pentos.proto")
@EnableWebMvc
@EnableTransactionManagement
public class AppConfig {
private static final Logger log = LoggerFactory.getLogger(AppConfig.class);
private static Properties getHibernateProperties() {
final Properties properties = new Properties();
properties.put("hibernate.show_sql", "true");
// properties.put("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");
properties.put("hibernate.dialect", "org.hibernate.dialect.MySQL5Dialect");
properties.put("hbm2ddl.auto", "create");
return properties;
}
{
log.debug("Here am I: {}");
}
@Bean(name = "dataSource")
public DataSource getDataSource() {
final DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/myschema");
dataSource.setUsername("user");
dataSource.setPassword("password");
return dataSource;
}
@Inject
@Bean(name = "sessionFactory")
public SessionFactory getSessionFactory(final DataSource dataSource) {
final LocalSessionFactoryBuilder sessionBuilder = new LocalSessionFactoryBuilder(dataSource);
sessionBuilder.addAnnotatedClasses(User.class);
sessionBuilder.addProperties(getHibernateProperties());
return sessionBuilder.buildSessionFactory();
}
@Inject
@Bean(name = "transactionManager")
public HibernateTransactionManager getTransactionManager(final SessionFactory sessionFactory) {
final HibernateTransactionManager transactionManager = new HibernateTransactionManager(
sessionFactory);
return transactionManager;
}
}
除使用带注释的类外,它工作得很好.
如何将hbm / user.xml添加到sessionBuilder?
我尝试了在某些示例中找到的Configuration类,但是不推荐使用buildSessionFactory()方法.
我还尝试了ServiceRegistry描述的here,但是随后丢失了我的数据源方法,并且如果没有数据源,系统将无法设置HibernateTransactionManager.
没有HibernateTransactionManager,我将无法使用@Transactional,而且我不喜欢手动打开和关闭交易.
目前,我正在圈子中旋转,确实需要帮助才能使其正常工作.我已经考虑过放弃Hibernate并使用我的旧MyBatis方法,但是您知道,我喜欢学习新知识…
解决方法:
将xml文件作为资源添加到SessionFactory,如下所示:
@Inject
@Bean(name = "sessionFactory")
public SessionFactory getSessionFactory(final DataSource dataSource) {
final LocalSessionFactoryBuilder sessionBuilder = new LocalSessionFactoryBuilder(dataSource);
sessionBuilder.addResource("/path-to-/hbm/user.xml");
sessionBuilder.addAnnotatedClasses(User.class);
sessionBuilder.addProperties(getHibernateProperties());
return sessionBuilder.buildSessionFactory();
}
标签:hibernate,hibernate-5-x,xml,spring,java 来源: https://codeday.me/bug/20191119/2037734.html