标签归档:Hibernate

Hibernate实体关联查询方法

            在项目中经常要多个实体中查询数据,下面使用Hibernate实体关联查询方法:

DetachedCriteria criteria =DetachedCriteria .forClass(Org.class);
DetachedCriteria staffCeiteria = DetachedCriteria.forClass(Staff.class);
staffCeiteria.setProjection(Property.forName("id"));
staffCeiteria.add(Restrictions.ilike("name",createName,MatchMode.ANYWHERE));
criteria.add(Property.forName("created").in(staffCeiteria));

case by: java.lang.NoSuchMethodError: javax.persistence.OneToMany.orphanRemoval()Z

使用hibernate-distribution-3.6.9.Final-dist包时出现如下错误:

java.lang.NoSuchMethodError: javax.persistence.OneToOne.orphanRemoval()Z
at org.hibernate.cfg.AnnotationBinder.processElementAnnotations(AnnotationBinder.java:1641)
at org.hibernate.cfg.AnnotationBinder.processIdPropertiesIfNotAlready(AnnotationBinder.java:796)
at org.hibernate.cfg.AnnotationBinder.bindClass(AnnotationBinder.java:707)
at org.hibernate.cfg.Configuration$MetadataSourceQueue.processAnnotatedClassesQueue(Configuration.java:4035)
at org.hibernate.cfg.Configuration$MetadataSourceQueue.processMetadata(Configuration.java:3989)
at org.hibernate.cfg.Configuration.secondPassCompile(Configuration.java:1398)
at org.hibernate.cfg.Configuration.generateDropSchemaScript(Configuration.java:1002)
at org.hibernate.tool.hbm2ddl.SchemaExport.(SchemaExport.java:130)
at org.hibernate.tool.hbm2ddl.SchemaExport.(SchemaExport.java:92)
at com.cloudcode.tk.test.HibernateORMappingTest.testSchemaExport(HibernateORMappingTest.java:39)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:76)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184)
at org.junit.runners.ParentRunner.run(ParentRunner.java:236)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:49)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)

1解决办法:hibernate-jpa-2.0-api-1.0.1.Final.jar 与ejb3-persistence.jar 有冲突,可以把ejb3-persistence删除,


java.lang.NoClassDefFoundError: javassist/util/proxy/MethodFilter

org.hibernate.HibernateException: Unable to instantiate default tuplizer [org.hibernate.tuple.entity.PojoEntityTuplizer]
at org.hibernate.tuple.entity.EntityTuplizerFactory.constructTuplizer(EntityTuplizerFactory.java:108)
at org.hibernate.tuple.entity.EntityTuplizerFactory.constructDefaultTuplizer(EntityTuplizerFactory.java:133)
at org.hibernate.tuple.entity.EntityEntityModeToTuplizerMapping.<init>(EntityEntityModeToTuplizerMapping.java:80)
at org.hibernate.tuple.entity.EntityMetamodel.<init>(EntityMetamodel.java:322)
at org.hibernate.persister.entity.AbstractEntityPersister.<init>(AbstractEntityPersister.java:485)
at org.hibernate.persister.entity.SingleTableEntityPersister.<init>(SingleTableEntityPersister.java:133)
at org.hibernate.persister.PersisterFactory.createClassPersister(PersisterFactory.java:84)
at org.hibernate.impl.SessionFactoryImpl.<init>(SessionFactoryImpl.java:286)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1872)
at com.cloudcode.tk.junit.StudentTest.test(StudentTest.java:19)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:76)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184)
at org.junit.runners.ParentRunner.run(ParentRunner.java:236)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:49)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
Caused by: java.lang.reflect.InvocationTargetException
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at org.hibernate.tuple.entity.EntityTuplizerFactory.constructTuplizer(EntityTuplizerFactory.java:105)
… 31 more
Caused by: java.lang.NoClassDefFoundError: javassist/util/proxy/MethodFilter
at org.hibernate.bytecode.javassist.BytecodeProviderImpl.getProxyFactoryFactory(BytecodeProviderImpl.java:49)
at org.hibernate.tuple.entity.PojoEntityTuplizer.buildProxyFactoryInternal(PojoEntityTuplizer.java:205)
at org.hibernate.tuple.entity.PojoEntityTuplizer.buildProxyFactory(PojoEntityTuplizer.java:183)
at org.hibernate.tuple.entity.AbstractEntityTuplizer.<init>(AbstractEntityTuplizer.java:167)
at org.hibernate.tuple.entity.PojoEntityTuplizer.<init>(PojoEntityTuplizer.java:77)
… 36 more
Caused by: java.lang.ClassNotFoundException: javassist.util.proxy.MethodFilter
at java.net.URLClassLoader$1.run(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
… 41 more

 把包javassist-3.12.0.GA.jar加入

User Spring And Hibernate With MongoDB


The first thing to do is to install MongoDB on your machine (unfortunately it is not yet possible to run it embedded so we use a local instance instead). For installation see this.One of the requirements we have for one of our Mule ESB implementations is to log the messages that went through the ESB (especially handy during development and testing). There has been written a lot already about logging with Mule so I am not going to discuss that again. In this post I’ll only show you how you can use Spring/Hibernate and MongoDB to store your messages in the MongoDB, because a document-oriented database like MongoDB is a nice fit for this requirement.

After MongoDB is installed we can create a new standard Maven project and modify the generated pom.xml to the following pom.xml.

Next step is the creation of the Hibernate Entity class like this: 

package nl.redstream.mongo.entity;
 
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import org.bson.types.ObjectId;
 
/**
 * Model object 
 * @author pascal
 */
@Entity
@Table(name = "logItems")
public class LogItem implements Serializable {
 
    @Id
    private ObjectId id;
    private String message;
    private String timestamp;
 
    public ObjectId getId() {
        return id;
    }
 
    public void setId(ObjectId id) {
        this.id = id;
    }
 
    public String getMessage() {
        return message;
    }
 
    public void setMessage(final String message) {
        this.message = message;
    }
 
    public String getTimestamp() {
        return timestamp;
    }
 
    public void setTimestamp(final String timestamp) {
        this.timestamp = timestamp;
    }
 
    @Override
    public String toString() {
        return "LogItem [id=" + id + ", message=" + message + ", timestamp=" + timestamp + "]";
    }
}

As you might notice I have used the ObjectId as primary Id. I was forced to this by bug DATADOC-176 which only recently got fixed.

The Dao and Service object classes that are used to access the MongoDB are:

Now wire this all together with the following spring config files:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation=
               "http://www.springframework.org/schema/beans
                http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
 
    <import resource="spring-mongodb-config.xml"/>
 
    <bean id="logService" class="nl.redstream.mongo.services.MongoDBLoggerServiceImpl">
        <property name="dao" ref="logDao"/>
    </bean>
    <bean id="logDao" class="nl.redstream.mongo.dao.LogItemDaoImpl">
        <property name="mongoTemplate" ref="mongoTemplate"/>
    </bean>
</beans>

and the ‘spring-mongodb-config.xml’ (as described here):

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:mongo="http://www.springframework.org/schema/data/mongo"
       xsi:schemaLocation=
               "http://www.springframework.org/schema/beans
                http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
                http://www.springframework.org/schema/data/mongo
                http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd">
 
    <!-- Default bean name is 'mongo' -->
    <mongo:mongo host="localhost" port="27017">
        <!-- OPTIONAL: configure <mongo:options /> -->
    </mongo:mongo>
 
    <mongo:db-factory dbname="redstream" mongo-ref="mongo"/>
 
    <bean id="mongoTemplate" class="org.springframework.data.document.mongodb.MongoTemplate">
        <constructor-arg ref="mongoDbFactory"/>
    </bean>
</beans>

That’s it. Now you have a foundation to start using MongoDB with Spring and Hibernate classes. In the next post I will show how you can test this setup without manually having to start and stop MongoDB.This article comes from:http://www.redstream.nl/2011/07/14/use-spring-and-hibernate-with-mongodb/