我在Hibernate 4中生成会话工厂时遇到了麻烦.在Hibernate 3中我简单地做了:
org.hibernate.cfg.Configuration conf= HibernateUtil
.getLimsInitializedConfiguration(systemConfiguration
.getHibernateconfFile());
SessionFactory sf = conf.configure().buildSessionFactory();
Run Code Online (Sandbox Code Playgroud)
现在我需要将ServiceRegistry类传递给buildSessionFactory,但是Javadocs对于如何解决这个问题非常模糊.有小费吗?
我有两个关于@JoinFormula和@OneToMany注释的问题:
如何用注释@JoinFormula
和@OneToMany
注释限制结果的数量?
我如何定义id
表达式author = id
中指的是Author.id
?
Author {
@Id
private Long id;
@OneToMany
@JoinFormula(value = "SELECT a FROM Article a WHERE author = id AND schedule < CURRENT_TIMESTAMP()") // limit = 15
private List<Article> pastArticles;
}
Run Code Online (Sandbox Code Playgroud)像这样,即使我删除schedule <
了条款的一部分,我仍然将pastArticles保持为空.
谢谢!
有没有办法我们可以使用JPA EntityManager使用批量插入.我知道没有直接的方法来实现这一目标,但必须有一些方法来实现这一机制.
实际上,对于每次插入操作,它需要300毫秒,我希望使用批量插入而不是单个插入来减少.
这是我正在使用的单个插入代码
@PersistenceContext(unitName = "testing")
EntityManager eM;
Query querys = this.eM.createNativeQuery(insertQuery);
for (String s : someList) {
//setting parameters
querys.executeUpdate();
}
Run Code Online (Sandbox Code Playgroud)
提前致谢.
MOTHER
感谢JPQL查询,我试图删除大量的行.
所述Mother
类的定义如下:
@Entity
@Table(name = "MOTHER")
public class Mother implements Serializable {
@OneToMany(cascade = CascadeType.ALL, mappedBy = "mother",
orphanRemoval = true)
private List<Child> children;
}
@Entity
@Table(name = "CHILD")
public class Child implements Serializable {
@ManyToOne
@JoinColumn(name = "MOTHER_ID")
private Mother mother;
}
Run Code Online (Sandbox Code Playgroud)
如您所见,Mother
该类具有"子",并在执行以下查询时:
String deleteQuery = "DELETE FROM MOTHER WHERE some_condition";
entityManager.createQuery(deleteQuery).executeUpdate();
Run Code Online (Sandbox Code Playgroud)
抛出异常:
ERROR - ORA-02292: integrity constraint <constraint name> violated -
child record found
Run Code Online (Sandbox Code Playgroud)
当然,我可以首先选择我要删除的所有对象,然后在迭代它之前将它们检索到列表中以删除所有检索到的对象,但是这样的解决方案的性能会很糟糕!
那么有没有办法利用前面的映射来有效地删除所有Mother
对象和Child
与它们相关的所有对象,而无需首先为所有子项编写查询?
我已经配置了两个持久性单元,实体管理器设置如下:
<bean id="liveEntityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
p:dataSource-ref="LiveDataSource">
<property name="persistenceUnitName" value="LivePersistenceUnit" />
</bean>
<bean id="archiveEntityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
p:dataSource-ref="ArchiveDataSource">
<property name="persistenceUnitName" value="ArchivePersistenceUnit" />
</bean>
Run Code Online (Sandbox Code Playgroud)
然后我将事务管理器配置为
<bean id="LiveTransactionManager"
class="org.springframework.orm.jpa.JpaTransactionManager"
p:entityManagerFactory-ref="liveEntityManagerFactory"/>
<bean id="ArchiveTransactionManager"
class="org.springframework.orm.jpa.JpaTransactionManager"
p:entityManagerFactory-ref="archiveEntityManagerFactory"/>
Run Code Online (Sandbox Code Playgroud)
我最初只配置了一个,它被称为"transactionManager".Addint一个额外的持久单元似乎会产生错误.有一点我不明白,如果我配置了两个持久性单元(每个用于一个单独的数据库),我是否还需要为每个数据源配置一个单独的实体管理器和一个事务管理器?
我得到的错误如下所示:(我搜索了所有文件,我找不到任何有"transactionManager"参考的地方)
org.springframework.ws.soap.client.SoapFaultClientException: No bean named 'transactionManager' is defined
at org.springframework.ws.soap.client.core.SoapFaultMessageResolver.resolveFault(SoapFaultMessageResolver.java:37)
at org.springframework.ws.client.core.WebServiceTemplate.handleFault(WebServiceTemplate.java:774)
at org.springframework.ws.client.core.WebServiceTemplate.doSendAndReceive(WebServiceTemplate.java:600)
at org.springframework.ws.client.core.WebServiceTemplate.sendAndReceive(WebServiceTemplate.java:537)
at org.springframework.ws.client.core.WebServiceTemplate.marshalSendAndReceive(WebServiceTemplate.java:384)
at org.springframework.ws.client.core.WebServiceTemplate.marshalSendAndReceive(WebServiceTemplate.java:378)
at org.springframework.ws.client.core.WebServiceTemplate.marshalSendAndReceive(WebServiceTemplate.java:370)
at com.ws.client.SoapTest.testFail(SoapTest.java:140)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
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.internal.runners.statements.RunBefores.evaluate(RunBefores.java:28)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:74)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:31)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:83)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:72) …
Run Code Online (Sandbox Code Playgroud) 我正在换掉一个用于MySQL的德比数据库.我以前一切都工作但是在我认为正确的配置之后我得到了错误:
引起:javax.resource.ResourceException:类名错误或类路径未设置为:com.mysql.jdbc.jdbc2.optional.MysqlDataSource
控制台的完整错误输出:
Caused by: javax.resource.ResourceException: Class name is wrong or classpath is not set for : com.mysql.jdbc.jdbc2.optional.MysqlDataSource
at com.sun.gjc.common.DataSourceObjectBuilder.getDataSourceObject(DataSourceObjectBuilder.java:292)
at com.sun.gjc.common.DataSourceObjectBuilder.constructDataSourceObject(DataSourceObjectBuilder.java:114)
at com.sun.gjc.spi.ManagedConnectionFactory.getDataSource(ManagedConnectionFactory.java:1292)
at com.sun.gjc.spi.DSManagedConnectionFactory.getDataSource(DSManagedConnectionFactory.java:148)
at com.sun.gjc.spi.DSManagedConnectionFactory.createManagedConnection(DSManagedConnectionFactory.java:101)
at com.sun.enterprise.resource.allocator.LocalTxConnectorAllocator.createResource(LocalTxConnectorAllocator.java:87)
Run Code Online (Sandbox Code Playgroud)
我已经仔细检查了一些名称,连接池和其他资源.我还在两个项目中将MySQL驱动程序.jars添加到glassfish库中.数据库肯定通过eclipse正常工作,因为我能够查看表并在eclipse的数据库上下文中显示资源.所以我知道至少那些司机正在正确地工作.persistence.xml文件看起来也不错.它引用了jdbc/mydatabase jndi引用,并且默认选择JTA作为manament类型.
有人有另一个建议吗?谢谢
有没有简单的解决方案在新线程中使用JPA将数据保存到数据库中?
我的基于Spring的Web应用程序允许用户管理计划任务.在运行时,他可以创建和启动预定义任务的新实例.我正在使用spring的TaskScheduler,一切运行良好.
但我需要将每个已触发任务的布尔结果保存到数据库中.我怎样才能做到这一点?
编辑:我必须概括我的问题:我需要从任务中调用我的@Service类的方法.因为在保存到数据库之前必须"处理"任务结果.
编辑2:我的问题代码的简化版本来到这里.从调度程序调用saveTaskResult()时,将打印出消息,但不会将任何内容保存到db中.但每当我从控制器调用saveTaskResult()时,记录都会正确保存到数据库中.
@Service
public class DemoService {
@Autowired
private TaskResultDao taskResultDao;
@Autowired
private TaskScheduler scheduler;
public void scheduleNewTask() {
scheduler.scheduleWithFixedDelay(new Runnable() {
public void run() {
// do some action here
saveTaskResult(new TaskResult("result"));
}
}, 1000L);
}
@Transactional
public void saveTaskResult(TaskResult result) {
System.out.println("saving task result");
taskResultDao.persist(result);
}
}
Run Code Online (Sandbox Code Playgroud) 我花了几天时间试图为我的Spring/JPA(Hibernate)集成测试找到一个有效的数据库连接,排除神秘的"没有发现数据库上下文"错误,我终于让它工作了,但我不明白我为什么要这样做做我做的.
请注意我的LocalContainerEntityManagerFacotryBean如何引用HibernateJpaVendorAdapter.
<bean class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean" id="myEMF">
<property name="persistenceXmlLocation" value="file:src/test/resources/META-INF/persistence.xml" />
<property name="persistenceUnitName" value="myPU" />
<property name="jpaVendorAdapter" ref="hibernateJpaAdapter" />
</bean>
<bean id="hibernateJpaAdapter" class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="true" />
</bean>
Run Code Online (Sandbox Code Playgroud)
为什么我用这个HibernateJpaVendorAdapter时,我的持久性单元已经配置了对Hibernate,如下图所示?
<persistence-unit name="myPU" transaction-type="RESOURCE_LOCAL">
<class>com.blah.blah.Class1</class>
<class>com.blah.blah.Class2</class>
<class>com.blah.blah.Class3</class>
<properties>
<property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver"/>
<property name="hibernate.connection.url" value="jdbc:mysql://127.0.0.1?zeroDateTimeBehavior=convertToNull"/>
<property name="hibernate.connection.username" value="uname"/>
<property name="hibernate.connection.password" value="pwd"/>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLInnoDBDialect" />
<property name="hibernate.hbm2ddl.auto" value="update" />
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.ejb.event.post-insert"
value="org.hibernate.ejb.event.EJB3PostInsertEventListener,org.hibernate.envers.event.AuditEventListener" />
<property name="hibernate.ejb.event.post-update"
value="org.hibernate.ejb.event.EJB3PostUpdateEventListener,org.hibernate.envers.event.AuditEventListener" />
<property name="hibernate.ejb.event.post-delete"
value="org.hibernate.ejb.event.EJB3PostDeleteEventListener,org.hibernate.envers.event.AuditEventListener" />
<property name="hibernate.ejb.event.pre-collection-update" …
Run Code Online (Sandbox Code Playgroud) 我正在尝试通过外键过滤结果集:
createCriteria(Person.class).add(Restrictions.ne("position", 1L)).list()
Run Code Online (Sandbox Code Playgroud)
但得到这个例外: org.hibernate.PropertyAccessException: could not get a field value by reflection getter of com.example.model.Position.id
以下是必要的JPA实体(修剪到必要的字段):
@Entity
@Table
public class Person {
@Id
@GeneratedValue
private Long id;
@ManyToOne
@JoinColumn(nullable = false)
@ForeignKey(name = "person_position_fkey")
private Position position;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Position getPosition() {
return position;
}
public void setPosition(Position position) {
this.position = position;
}
}
@Entity
@Table
public class Position {
@Id
@GeneratedValue
private …
Run Code Online (Sandbox Code Playgroud) 我有一个存储库接口,其中包含一些使用@Query注释的抽象方法.现在我想为这些查询添加限制和偏移支持.
例:
public interface ProductRepository
extends CrudRepository<Product, Long> {
@Query("from Product")
List<Product> findAllProducts();
}
Run Code Online (Sandbox Code Playgroud)
这样的事情会很好
public interface ProductRepository
extends CrudRepository<Product, Long> {
@Query("from Product limit :limit ")
List<Product> findAllProducts(@Param("limit") Integer limit);
}
Run Code Online (Sandbox Code Playgroud)
但这不起作用.有一个解决方案,我创建了一个接口的实现(http://stackoverflow.com/questions/3479128/jpql-limit-number-of-results)但我不知道是否有可能添加偏移和限制查询或是否有注释.