我正在尝试使用Simple Spring启动应用程序来创建用户并使用Hibernate将它们保存到数据库中,但是我收到了这个错误。
你能指导我解决这个问题吗?
引起:org.springframework.beans.factory.BeanCreationException: 使用name' jpaMappingContext':init的调用创建bean时出错 方法失败;嵌套异常是java.lang.IllegalArgumentException: 必须至少存在一个JPA元模型!在 org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1628) 在 org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555) 在 org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483) 在 org.springframework.beans.factory.support.AbstractBeanFactory $ 1.getObject(AbstractBeanFactory.java:306)
我的申请包括: 的的pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.springboot</groupId>
<artifactId>SpringBootHibernateInt</artifactId>
<version>0.0.1-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.8.RELEASE</version>
<relativePath />
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
DataSource配置:
package com.spring.security.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.*;
import org.springframework.core.env.Environment;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.hibernate5.HibernateTransactionManager;
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import javax.sql.DataSource;
import java.util.Properties;
@Configuration
@EnableTransactionManagement
public class DataSourceConfig {
@Autowired
Environment env;
@Bean
public DataSource getDataSource() {
DriverManagerDataSource ds = new DriverManagerDataSource();
ds.setDriverClassName(env.getProperty("spring.datasource.driver-class-name"));
ds.setUrl(env.getProperty("spring.datasource.url"));
ds.setUsername(env.getProperty("spring.datasource.username"));
ds.setPassword(env.getProperty("spring.datasource.password"));
return ds;
}
@Bean
public Properties getHibernateProperties() {
Properties properties = new Properties();
properties.put("spring.hibernate.dialect", env.getProperty("spring.hibernate.dialect"));
properties.put("spring.hibernate.show-sql", env.getProperty("spring.hibernate.show-sql"));
properties.put("spring.hibernate.format-sql", env.getProperty("spring.hibernate.format-sql"));
properties.put("spring.hibernate.ddl-auto", env.getProperty("spring.hibernate.ddl-auto"));
return properties;
}
@Bean
@Autowired
public HibernateTransactionManager transactionManager() {
HibernateTransactionManager htm = new HibernateTransactionManager();
htm.setSessionFactory(getSessionFactory().getObject());
return htm;
}
@Bean
public LocalSessionFactoryBean getSessionFactory() {
LocalSessionFactoryBean lsfb = new LocalSessionFactoryBean();
lsfb.setDataSource(getDataSource());
lsfb.setHibernateProperties(getHibernateProperties());
// lsfb.setAnnotatedClasses(User.class);
lsfb.setPackagesToScan(env.getProperty("entitymanager.packagesToScan"));
return lsfb;
}
}
User.java
package com.spring.security.model;
import javax.persistence.*;
@Entity
@Table(name = "User")
public class User {
public User(String name) {
this.name = name;
}
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
UserDAOImpl.java
package com.spring.security.dao;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import com.spring.security.model.User;
@Repository
@Transactional
public class UserDAOImpl {
@Autowired
private SessionFactory sessionFactory;
public SessionFactory getSessionFactory() {
return sessionFactory;
}
public User findUser(String userName) {
return (User) sessionFactory.getCurrentSession()
.createQuery("from User where name = " + userName);
}
public void createUser(User user) {
sessionFactory.getCurrentSession()
.save(user);
}
}
控制器
package com.spring.security.web;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.spring.security.dao.UserDAOImpl;
import com.spring.security.model.User;
@Controller
public class HomeController {
@Autowired
private UserDAOImpl userService;
@RequestMapping(value = "/save")
@ResponseBody
public String create(String name) {
try {
User user = new User(name);
userService.createUser(user);
} catch (Exception ex) {
return ex.getMessage();
}
return "User succesfully saved!";
}
}
Run.java
package com.spring.security;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Run {
public static void main(String[] args) {
SpringApplication.run(Run.class, args);
}
}
Application.properties
################### JDBC Configuration ###############################
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3307/***
spring.datasource.username=***
spring.datasource.password=***
################### Hibernate Configuration ##########################
spring.hibernate.dialect=org.hibernate.dialect.MySQLDialect
spring.hibernate.show-sql=true
spring.hibernate.format-sql=true
spring.hibernate.ddl-auto=create
entitymanager.packagesToScan = com
答案 0 :(得分:0)
默认情况下Spring Boot启用数据源的自动配置类,你可以通过这样的方式禁用它。
@EnableAutoConfiguration(exclude = {DataSourceAutoConfiguration.class,JndiConnectionFactoryAutoConfiguration.class,
HibernateJpaAutoConfiguration.class,JpaRepositoriesAutoConfiguration.class,DataSourceTransactionManagerAutoConfiguration.class})
@ComponentScan
public class SpringBootStarter {
public static void main(String[] args) {
SpringApplication.run(MyBootApplication.class, args);
}
}
这可能对你有所帮助:)。
答案 1 :(得分:0)
正如我在评论中所说,您可以删除所有手动数据源配置,因为Spring Boot会自动为您配置它。您还可以使用JPA存储库来满足您的需求。用新的存储库接口替换UserDaoImpl类:
<div class="flex">
<div>
<a class="flex collapsed" ng-class="{'accordion-toggle collapsed':item.beneficiaries.length>0}" ng-if="item.beneficiaries.length>0" data-toggle="collapse" href="#{{item.benefit_type_sysID}}" role="button" aria-expanded="false" aria-controls="collapseDetails">
<span class="h4" >{{item.benefit_type_name}}</span>
</a>
<h1 class="h4 flex collapsed" ng-if="item.beneficiaries.length==0">
{{item.benefit_type_name}}
</h1>
</div>
<div style="margin-left:auto;">
<button title="Add a beneficiary" type="button" class="btn btn-primary text-uppercase" ng-if="item.beneficiaries.length==0" ng-click="c.newEntry(-1, 'sn_hr_core_beneficiary','newBene')">Add Beneficiary</button>
<i title="Beneficiaries total 100%" class="fa-2x fa fa-check-circle success" aria-hidden="true" ng-if="item.beneficiaries.length>0 && item.percent_total==100"></i>
<i title="Beneficiaries do NOT total 100%" class="fa-2x fa fa-exclamation-circle warning" aria-hidden="true" ng-if="item.beneficiaries.length>0 && item.percent_total!=100"></i>
</div>
</div>
然后在你的控制器中:
@Repository
interface UserRepository implements CrudRepository<User, Integer> {
User findByName(String name);
}
如果你真的想使用Hibernate SessionFactory,你可以执行以下操作:
@Controller
public class HomeController {
@Autowired
private UserRepository userService;
@RequestMapping(value = "/save")
@ResponseBody
public String create(String name, String city) {
try {
User user = new User("JAYESH");
userService.save(user);
} catch (Exception ex) {
return ex.getMessage();
}
return "User succesfully saved!";
}
}