我到处搜索,但我没有找到一个好的答案 我正在使用Hibernate + Spring + Mysql开发maven应用程序 这是我的application-context.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http:...">
<bean id='dataSource' class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost/university"/>
<property name="username" value="root"/>
<property name="password" value="admin"/>
</bean>
<bean id='sessionFactory' class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="annotatedClasses">
<list>
<value>com.university.entities.Course</value>
<value>com.university.entities.Student</value>
<value>com.university.entities.Teacher</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLInnoDBDialect</prop>
</props>
</property>
</bean>
<bean id='transactionManager' class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref='sessionFactory'/>
</bean>
<tx:annotation-driven transaction-manager="transactionManager"/>
<context:annotation-config/>
<context:component-scan base-package="com.university.dao"></context:component-scan>
</beans>
这是我的pom.xml:
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<spring.version>3.2.4.RELEASE</spring.version>
<hibernate.version>3.6.7.Final</hibernate.version>
<jsf.version>2.2.4</jsf.version>
<slf4j.version>1.7.1</slf4j.version>
<primefaces.version>4.0</primefaces.version>
</properties>
<dependencies>
<!-- Tests unitaires avec junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.10</version>
<scope>test</scope>
</dependency>
<!-- Spring 3 dependencies -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${spring.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
<scope>test</scope>
</dependency>
<!-- antlr -->
<dependency>
<groupId>org.antlr</groupId>
<artifactId>antlr</artifactId>
<version>3.5.1</version>
</dependency>
<!-- Package entities -->
<dependency>
<groupId>javax.persistence</groupId>
<artifactId>persistence-api</artifactId>
<version>1.0-rev-1</version>
<scope>provided</scope>
</dependency>
<!-- Hibernate -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-commons-annotations</artifactId>
<version>3.2.0.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.0-api</artifactId>
<version>1.0.0.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>${hibernate.version}</version>
<scope>runtime</scope>
</dependency>
<!-- JSF dependencies -->
<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-api</artifactId>
<version>${jsf.version}</version>
</dependency>
<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-impl</artifactId>
<version>${jsf.version}</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!-- Primefaces dependency -->
<dependency>
<groupId>org.primefaces</groupId>
<artifactId>primefaces</artifactId>
<version>${primefaces.version}</version>
</dependency>
<!-- slf4j -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>${slf4j.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>${slf4j.version}</version>
</dependency>
<!-- commons -->
<dependency>
<groupId>commons-collections</groupId>
<artifactId>commons-collections</artifactId>
<version>3.1</version>
</dependency>
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.0</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<groupId>commons-pool</groupId>
<artifactId>commons-pool</artifactId>
<version>1.5.4</version>
</dependency>
<dependency>
<groupId>commons-beanutils</groupId>
<artifactId>commons-beanutils</artifactId>
<version>1.8.3</version>
</dependency>
<!-- log4j -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.15</version>
</dependency>
<!-- javassist -->
<dependency>
<groupId>javassist</groupId>
<artifactId>javassist</artifactId>
<version>3.12.1.GA</version>
</dependency>
<!-- mysql -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.16</version>
<dependencies>
<dependency>
<groupId>org.apache.maven.surefire</groupId>
<artifactId>surefire-junit47</artifactId>
<version>2.16</version>
</dependency>
</dependencies>
</plugin>
</plugins>
</build>
但是当我尝试将一个简单的DAO测试为:
package com.university.dao.test;
import java.util.List;
import junit.framework.TestCase;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.university.dao.StudentDAO;
import com.university.entities.Student;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:application-context.xml" })
public class StudentDAOTest extends TestCase {
private static Log LOG = LogFactory.getLog(StudentDAOTest.class);
@Autowired
private StudentDAO studentDAO;
@Test
public void testFindAll() {
List<Student> listStudent = studentDAO.findAll();
LOG.debug(listStudent);
assertNotNull(listStudent);
}
@Test
public void testCreateOrUpdate() {
Student newStudent = new Student("Abderrahmen ISSA", "07701607");
studentDAO.createOrUpdate(newStudent);
assertNotNull(newStudent.getId());
}
@Test
public void testFindById() {
Integer id = 2;
Student student = studentDAO.findById(id);
assertNotNull(student);
}
@Test
public void testRemove() {
Student userToRemove = new Student("User To Test Remove", "11111111");
studentDAO.createOrUpdate(userToRemove);
Integer id = userToRemove.getId();
studentDAO.remove(userToRemove);
Student student = studentDAO.findById(id);
assertNull(student);
}
}
学生班是:
package com.university.entities;
// Generated 20 oct. 2013 20:53:03 by Hibernate Tools 3.4.0.CR1
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import static javax.persistence.GenerationType.IDENTITY;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
/**
* Student generated by hbm2java
*/
@Entity
@Table(name = "student", catalog = "university")
public class Student implements java.io.Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private Integer id;
private String name;
private String mail;
private Date birthDate;
private String birthPlace;
private String cin;
private Integer mobile;
private Set<Course> courses = new HashSet<Course>(0);
public Student() {
}
public Student(String mail, String cin) {
this.mail = mail;
this.cin = cin;
}
public Student(String name, String mail, Date birthDate, String birthPlace,
String cin, Integer mobile, Set<Course> courses) {
this.name = name;
this.mail = mail;
this.birthDate = birthDate;
this.birthPlace = birthPlace;
this.cin = cin;
this.mobile = mobile;
this.courses = courses;
}
@Id
@GeneratedValue(strategy = IDENTITY)
@Column(name = "id", unique = true, nullable = false)
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
@Column(name = "name", length = 45)
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
@Column(name = "mail", nullable = false, length = 45)
public String getMail() {
return this.mail;
}
public void setMail(String mail) {
this.mail = mail;
}
@Temporal(TemporalType.DATE)
@Column(name = "birthDate", length = 10)
public Date getBirthDate() {
return this.birthDate;
}
public void setBirthDate(Date birthDate) {
this.birthDate = birthDate;
}
@Column(name = "birthPlace", length = 45)
public String getBirthPlace() {
return this.birthPlace;
}
public void setBirthPlace(String birthPlace) {
this.birthPlace = birthPlace;
}
@Column(name = "cin", nullable = false, length = 45)
public String getCin() {
return this.cin;
}
public void setCin(String cin) {
this.cin = cin;
}
@Column(name = "mobile")
public Integer getMobile() {
return this.mobile;
}
public void setMobile(Integer mobile) {
this.mobile = mobile;
}
@ManyToMany(fetch = FetchType.LAZY)
@JoinTable(name = "course_has_student", catalog = "university", joinColumns = { @JoinColumn(name = "Student_id", nullable = false, updatable = false) }, inverseJoinColumns = { @JoinColumn(name = "Course_id", nullable = false, updatable = false) })
public Set<Course> getCourses() {
return this.courses;
}
public void setCourses(Set<Course> courses) {
this.courses = courses;
}
@Override
public String toString() {
return "Student [name=" + name + ", mail=" + mail + ", cin=" + cin
+ "]";
}
}
StudentDAOImpl:
package com.university.dao.impl;
import org.springframework.stereotype.Repository;
import com.university.dao.StudentDAO;
import com.university.entities.Student;
@Repository("studentDAO")
public class StudentDAOImpl extends GenericDAOImpl<Student> implements
StudentDAO {
}
GenericDAOImpl:
package com.university.dao.impl;
import java.lang.reflect.ParameterizedType;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import com.university.dao.GenericDAO;
@Transactional
public abstract class GenericDAOImpl<T> implements GenericDAO<T> {
@Autowired
protected SessionFactory sessionFactory;
/**
* Unit.
*/
private final Class<T> entityBeanType;
/**
* Instantiates a new GenericServiceImpl.
*/
@SuppressWarnings("unchecked")
public GenericDAOImpl() {
this.entityBeanType = (Class<T>) ((ParameterizedType) getClass()
.getGenericSuperclass()).getActualTypeArguments()[0];
}
public SessionFactory getSessionFactory() {
return sessionFactory;
}
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
protected final Session getCurrentSession() {
if (sessionFactory == null) {
throw new IllegalStateException(
"Session Factory has not been set on DAO before usage");
}
return sessionFactory.getCurrentSession();
}
/**
* Gets the entity bean type.
*
* @return the entity bean type
*/
public final Class<T> getEntityBeanType() {
return entityBeanType;
}
public void createOrUpdate(T entity) {
getCurrentSession().saveOrUpdate(entity);
}
@SuppressWarnings("unchecked")
public List<T> findAll() {
return getCurrentSession().createQuery(
"from " + getEntityBeanType().getName()).list();
}
@SuppressWarnings("unchecked")
public T findById(Integer id) {
T entity = (T) getCurrentSession().get(getEntityBeanType(), id);
return entity;
}
public void remove(T entity) {
getCurrentSession().delete(entity);
}
}
我可以在日食上运行DAOTest但是通过mvn测试我得到了:
org.springframework.beans.factory.BeanCreationEception:错误 在类路径中定义名为'sessionFactory'的bean resource [application-context.xml]:init方法的调用失败; 嵌套异常是java.lang.NoSuchMethodError: javax.persistence.OneToMany.orphanRemoval&LT;&GT;ž
请帮忙!
答案 0 :(得分:1)
你有图书馆冲突。您是否已将其设置为Eclipse中的Hibernate项目,以便Eclipse将必要的JAR添加到类路径中?这可以解释为什么它在Eclipse中工作,而不是在Maven构建中工作。
无论如何,确保Hibernate库版本匹配,例如4.1.8.Final并删除javax.persistence-api依赖。
这就是你在POM中对Hibernate所需要的全部内容。其他一切都将由Maven传递解决。
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>${hibernate.version}</version>
</dependency>