I have a method loading up a persistent object and then have it updated. When I use flush(), the process hangs with no errors. Any idea?
Code:
public Task changeStatus(Long taskNo, String status) {
Session sess = HibernateUtil
.getSessionFactory()
.openSession();
Task task = (Task) sess.load(Task.class, taskNo);
task.setStatus(status);
sess.flush();
return task;
}
The log shows this:
INFO: 09:33:05,329 DEBUG Printer:83 - listing entities:
INFO: 09:33:05,329 DEBUG Printer:90 - models.Task{userByAssignedToCheck=null, client=models.Client#1, status=Withdrawn, datasets=, urgent=false, taskLogs=, userByCheckedBy=null, dateReceived=29 August 2013, dateCompleted=null, fee=null, onTime=false, userByOriginatorId=models.User#1, taskCat=null, userByAssignedToWork=null, source=null, originatorOld=null, description=null, userByCompletedBy=null, method=null, taskNo=11492, dueDate=null, requestVia=null, comments=}
INFO: 09:33:05,329 DEBUG AbstractBatcher:366 - about to open PreparedStatement (open PreparedStatements: 0, globally: 0)
INFO: 09:33:05,329 DEBUG SQL:401 - /* update models.Task */ update DBAKZHU0.INFO_TASK set CLIENTNO=?, ASSIGNEDTOCHECK=?, TASKTYPENO=?, COMPLETEDBY=?, CHECKEDBY=?, ORIGINATORID=?, SOURCENO=?, ASSIGNEDTOWORK=?, METHOD=?, REQUESTVIA=?, DATERECEIVED=?, DATECOMPLETED=?, DUEDATE=?, STATUS=?, ORIGINATOROLD=?, ONTIME=?, URGENT=?, FEE=?, DESCRIPTION=? where TASKNO=?
INFO: Hibernate: /* update models.Task */ update DBAKZHU0.INFO_TASK set CLIENTNO=?, ASSIGNEDTOCHECK=?, TASKTYPENO=?, COMPLETEDBY=?, CHECKEDBY=?, ORIGINATORID=?, SOURCENO=?, ASSIGNEDTOWORK=?, METHOD=?, REQUESTVIA=?, DATERECEIVED=?, DATECOMPLETED=?, DUEDATE=?, STATUS=?, ORIGINATOROLD=?, ONTIME=?, URGENT=?, FEE=?, DESCRIPTION=? where TASKNO=?
Related
I use JHipster to make a simple app and write a service, code as follows:
#Service
#Transactional
public class OperateQueueActionService {
#Transactional(rollbackFor = Throwable.class)
public OperateQueueDTO apply(OperateQueueDTO operateQueueDTO, QueueEventType queueEventType, String deskNo) {
StateMachine<QueueStatus, QueueEventType> stateMachine = operateQueueActionMachineService.getStateMachine();
try { QueueEventDTO operateQueueEventDTO = operateQueueUtils.saveQueueEvent(operateQueueDTO, queueEventType, deskNo);
......in process will throw RuntimeException.
} finally {
stateMachine.stop();
}
}
}
I want the transaction to rollback and not save queueEvent, but the record is saved in the database. This is the transaction log:
[2018-07-24 12:04:51.861] [XNIO-2 task-6] WARN
o.s.s.l.CompositeStateMachineListener -Error during stateContext
java.lang.RuntimeException: 无效状态 at
com.higoee.queue.state.utils.OperateQueueStateMachineLogListener.stateContext(OperateQueueStateMachineLogListener.java:58)
at java.lang.Thread.run(Thread.java:745) [2018-07-24 12:04:51.871]
[XNIO-2 task-6] INFO c.h.q.s.u.OperateQueueStateMachineLogListener
-4d667539-3316-491d-a0db-240e29b0fcae状态机状态为:STATEMACHINE_STOP [2018-07-24 12:04:51.872] [XNIO-2 task-6] DEBUG
o.s.orm.jpa.JpaTransactionManager -Initiating transaction commit
[2018-07-24 12:04:51.874] [XNIO-2 task-6] DEBUG
o.s.orm.jpa.JpaTransactionManager -Committing JPA transaction on
EntityManager
JPA config have not problem,spring state machine had been catch the exception which was thrown in StateMachineListenerAdapter.
I am trying to insert some objects in a BatchUpdate operation into the H2 Db with Spring Boot, and I am having problems doing so. The implementation does not think that the table is created. I get an error stack trace given below.
org.springframework.jdbc.BadSqlGrammarException: PreparedStatementCallback; bad SQL grammar
[INSERT INTO Expired_Chats(chat_id, username, chat_text, expiration_date) VALUES(?, ?, ?, ?)]; nested exception is org.h2.jdbc.JdbcSQLException: Table "EXPIRED_CHATS" not found; SQL statement:
INSERT INTO Expired_Chats(chat_id, username, chat_text, expiration_date) VALUES(?, ?, ?, ?) [42102-196]
I realise that the table is not being created, but I don't know why. According to the Spring Boot documentation, and I quote
Spring Boot can automatically create the schema (DDL scripts) of your DataSource and initialize it (DML scripts): it loads SQL from the standard root classpath locations schema.sql and data.sql, respectively.
My schema.sql is given below. It attempts to create two tables Chats and Expired_Chats. Each SQL statement is on a separate line for purposes of readability.
CREATE TABLE IF NOT EXISTS Chats(username VARCHAR(20), chat_text VARCHAR(256), chat_id NOT NULL BIGINT, expiration_date TIMESTAMP, PRIMARY KEY(chat_id));
CREATE INDEX IF NOT EXISTS username_index on Chats(username);
CREATE INDEX IF NOT EXISTS chat_id_index on Chats(chat_id);
CREATE INDEX IF NOT EXISTS expiration_date_index on Chats(expiration_date);
CREATE TABLE IF NOT EXISTS Expired_Chats(username VARCHAR(20), chat_text VARCHAR(256), chat_id NOT NULL BIGINT, expiration_date TIMESTAMP, PRIMARY KEY(chat_id));
CREATE INDEX IF NOT EXISTS username_index on Expired_Chats(username);
CREATE INDEX IF NOT EXISTS chat_id_index on Expired_Chats(chat_id);
CREATE INDEX IF NOT EXISTS expiration_date_index on Expired_Chats(expiration_date);
When I run my unit test in Eclipse, I see the following console log. Both schema.sql and cleanup.sql are being executed.
2017-11-08 18:16:26.635 INFO 24851 --- [ main] o.s.jdbc.datasource.init.ScriptUtils : Executing SQL script from class path resource [schema.sql]
2017-11-08 18:16:26.637 INFO 24851 --- [ main] o.s.jdbc.datasource.init.ScriptUtils : Executed SQL script from class path resource [schema.sql] in 2 ms.
2017-11-08 18:16:26.639 DEBUG 24851 --- [ main] c.underarmour.assignment.ChatRecordDao : Inserting 1 record(s) into the expired chat table.
2017-11-08 18:16:26.639 DEBUG 24851 --- [ main] c.underarmour.assignment.ChatRecordDao : Triggering 1 batch insert(s) to expired chat table.
2017-11-08 18:16:26.651 INFO 24851 --- [ main] o.s.b.f.xml.XmlBeanDefinitionReader : Loading XML bean definitions from class path resource [org/springframework/jdbc/support/sql-error-codes.xml]
2017-11-08 18:16:26.723 INFO 24851 --- [ main] o.s.jdbc.support.SQLErrorCodesFactory : SQLErrorCodes loaded: [DB2, Derby, H2, HSQL, Informix, MS-SQL, MySQL, Oracle, PostgreSQL, Sybase, Hana]
I am trying to insert data into the database using the following code. It uses Spring JDBC's Batch Update APIs.
public void insertDataInExpiredTable(Set<ChatRecord> chatRecords) {
StringBuilder sb = new StringBuilder();
sb.append("INSERT INTO Expired_Chats(chat_id, username, chat_text, expiration_date) ");
sb.append("VALUES(?, ?, ?, ?)");
Instant instant = Instant.now();
ZonedDateTime zt = instant.atZone(ZoneOffset.UTC);
List<ChatRecord> allRecords = new ArrayList<>(chatRecords);
for (int i = 0; i < allRecords.size(); i++) {
this.jdbcTemplate.batchUpdate(sb.toString(), new BatchPreparedStatementSetter() {
#Override
public void setValues(PreparedStatement ps, int i) throws SQLException {
ps.setLong(1, allRecords.get(i).getChatId());
ps.setString(2, allRecords.get(i).getUsername());
ps.setString(3, allRecords.get(i).getText());
ps.setTimestamp(4, Timestamp.from(zt.toInstant()));
}
#Override
public int getBatchSize() {
// TODO Auto-generated method stub
return 100;
}
});
}
}
My unit test configuration is as follows
#RunWith(SpringJUnit4ClassRunner.class)
#SpringBootTest(classes= {ChatRecordDao.class})
#Sql(executionPhase=ExecutionPhase.BEFORE_TEST_METHOD,scripts="classpath:/schema.sql")
#Sql(executionPhase=ExecutionPhase.AFTER_TEST_METHOD,scripts="classpath:/cleanup.sql")
public class ChatRecordDaoTest {
#Autowired
private DataSource dataSource;
#Autowired
private ChatRecordDao chatRecordDao;
#Test
public void testInsertDataInExpiredTable() throws Exception {
ChatRecord expected = new ChatRecord();
expected.setUsername("test");
expected.setText("text");
expected.setTimeout(14400);
expected.setChatId(1L);
Set<ChatRecord> expiredInserted = new LinkedHashSet<>();
expiredInserted.add(expected);
this.chatRecordDao.insertDataInExpiredTable(expiredInserted);
}
}
The clean up script consists of the following statements
DROP TABLE IF EXISTS Chats;DROP TABLE IF EXISTS Expired_Chats;
I am using Hibernate with Kotlin and I am having an issue with FetchType.LAZY on #ManyToOne relations. Consider following:
#ManyToOne(fetch = FetchType.LAZY)
open var event: Event?
The problem is that when FetchType.LAZY is used, the fetched Event will be of class Event_$$_jvst_... with JavaassistLazyInitializer on it. But the event will never be initialized, everything will be null or empty.
Once the FetchType.LAZY is removed, everything works correctly.
This didn't happen in Java.
I tried to add open on the var so that the Event can be correctly proxied. No effect.
All the #Entity classes are of course open as well. If the open keyword is removed, there will be no proxy created and so no laziness.
My guess is that Hibernate cannot easily proxy these default kotlin getters. Is there a way to solve it?
you could use this static method to deproxy your entity
/**
* Utility method that tries to properly initialize the Hibernate CGLIB
* proxy.
* #param <T>
* #param maybeProxy -- the possible Hibernate generated proxy
* #param baseClass -- the resulting class to be cast to.
* #return the object of a class <T>
* #throws ClassCastException
*/
public static <T> T deproxy(Object maybeProxy, Class<T> baseClass) throws ClassCastException {
if (maybeProxy instanceof HibernateProxy) {
return baseClass.cast(((HibernateProxy) maybeProxy).getHibernateLazyInitializer().getImplementation());
}
return baseClass.cast(maybeProxy);
}
I write a simple example to check your problem, and all works fine.
import org.hibernate.CacheMode
import org.hibernate.Session
import org.hibernate.SessionFactory
import org.hibernate.Transaction
import org.hibernate.boot.MetadataSources
import org.hibernate.boot.registry.StandardServiceRegistryBuilder
import org.hibernate.cfg.Environment
import java.util.*
import javax.persistence.*
fun main(args: Array<String>) {
val standardServiceRegistryBuilder = StandardServiceRegistryBuilder()
val settings = HashMap<String, String>().apply {
put(Environment.DRIVER, "org.h2.Driver")
put(Environment.URL, "jdbc:h2:mem:myDb;DB_CLOSE_DELAY=-1")
put(Environment.USER, "sa")
put(Environment.PASS, "sa")
put(Environment.DIALECT, "org.hibernate.dialect.H2Dialect")
put(Environment.SHOW_SQL, "true")
put(Environment.HBM2DDL_AUTO, "create")
}
val sessionFactory = standardServiceRegistryBuilder.applySettings(settings)
.build()
.let {
MetadataSources(it).apply {
addAnnotatedClass(History::class.java)
addAnnotatedClass(Event::class.java)
}
}
.run { metadataBuilder.build() }
.run { sessionFactoryBuilder.build() }
sessionFactory.inSession {
inTransaction { session ->
session.save(Event(1, "event description"))
session.save(History(1, Event(1), "history description"))
}
}
sessionFactory.inSession {
inTransaction { session ->
val entity = session.get(Event::class.java, 1L)
println("=============1=============")
println(entity)
}
}
sessionFactory.inSession {
inTransaction { session ->
val entity = session.load(History::class.java, 1L)
println("=============2=============")
println(entity)
}
}
}
private fun SessionFactory.inSession(function: Session.() -> Unit) {
val session = this.openSession()
session.function()
session.close()
}
private fun Session.inTransaction(function: Transaction.(s: Session) -> Unit) {
val transaction = this.beginTransaction()
transaction.function(this)
transaction.commit()
}
#Entity
open class History(
#Id
open var id: Long? = null,
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "eventId")
open var event: Event? = null,
open var description: String = ""
) {
override fun toString(): String {
return "History(id=$id, event=$event, description='$description')"
}
}
#Entity
open class Event(
#Id
open var id: Long? = null,
open var description: String? = null,
#OneToMany(fetch = FetchType.LAZY, mappedBy = "event")
open var history: MutableSet<History>? = null
) {
override fun toString(): String {
return "Event(id=$id, description='$description', history=${history?.size})"
}
}
Logs looks like this:
2017-12-05 18:43:03 [main] INFO org.hibernate.Version - HHH000412: Hibernate Core {5.2.12.Final}
2017-12-05 18:43:03 [main] INFO org.hibernate.cfg.Environment - HHH000206: hibernate.properties not found
2017-12-05 18:43:03 [main] INFO o.h.annotations.common.Version - HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
2017-12-05 18:43:04 [main] WARN o.hibernate.orm.connections.pooling - HHH10001002: Using Hibernate built-in connection pool (not for production use!)
2017-12-05 18:43:04 [main] INFO o.hibernate.orm.connections.pooling - HHH10001005: using driver [org.h2.Driver] at URL [jdbc:h2:mem:myDb;DB_CLOSE_DELAY=-1]
2017-12-05 18:43:04 [main] INFO o.hibernate.orm.connections.pooling - HHH10001001: Connection properties: {password=****, user=sa}
2017-12-05 18:43:04 [main] INFO o.hibernate.orm.connections.pooling - HHH10001003: Autocommit mode: false
2017-12-05 18:43:04 [main] INFO o.h.e.j.c.i.DriverManagerConnectionProviderImpl - HHH000115: Hibernate connection pool size: 20 (min=1)
2017-12-05 18:43:04 [main] INFO org.hibernate.dialect.Dialect - HHH000400: Using dialect: org.hibernate.dialect.H2Dialect
2017-12-05 18:43:04 [main] INFO o.h.validator.internal.util.Version - HV000001: Hibernate Validator 5.3.5.Final
WARNING: An illegal reflective access operation has occurred
WARNING: Illegal reflective access by javassist.util.proxy.SecurityActions (file:/Users/evgenyzaharov/.gradle/caches/modules-2/files-2.1/org.javassist/javassist/3.20.0-GA/a9cbcdfb7e9f86fbc74d3afae65f2248bfbf82a0/javassist-3.20.0-GA.jar) to method java.lang.ClassLoader.defineClass(java.lang.String,byte[],int,int,java.security.ProtectionDomain)
WARNING: Please consider reporting this to the maintainers of javassist.util.proxy.SecurityActions
WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations
WARNING: All illegal access operations will be denied in a future release
Hibernate: drop table Event if exists
2017-12-05 18:43:04 [main] INFO org.hibernate.orm.connections.access - HHH10001501: Connection obtained from JdbcConnectionAccess [org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess#56913163] for (non-JTA) DDL execution was not in auto-commit mode; the Connection 'local transaction' will be committed and the Connection will be set into auto-commit mode.
Hibernate: drop table History if exists
Hibernate: create table Event (id bigint not null, description varchar(255), primary key (id))
2017-12-05 18:43:04 [main] INFO org.hibernate.orm.connections.access - HHH10001501: Connection obtained from JdbcConnectionAccess [org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess#e8e0dec] for (non-JTA) DDL execution was not in auto-commit mode; the Connection 'local transaction' will be committed and the Connection will be set into auto-commit mode.
Hibernate: create table History (id bigint not null, description varchar(255), eventId bigint, primary key (id))
Hibernate: alter table History add constraint FK2yaqfgh2x1lsxcpbuifmd245k foreign key (eventId) references Event
2017-12-05 18:43:04 [main] INFO o.h.t.s.internal.SchemaCreatorImpl - HHH000476: Executing import script 'org.hibernate.tool.schema.internal.exec.ScriptSourceInputNonExistentImpl#6c15e8c7'
Hibernate: select event_.id, event_.description as descript2_0_ from Event event_ where event_.id=?
Hibernate: insert into Event (description, id) values (?, ?)
Hibernate: insert into History (description, eventId, id) values (?, ?, ?)
Hibernate: update History set description=?, eventId=? where id=?
Hibernate: select event0_.id as id1_0_0_, event0_.description as descript2_0_0_ from Event event0_ where event0_.id=?
=============1=============
Hibernate: select history0_.eventId as eventId3_1_0_, history0_.id as id1_1_0_, history0_.id as id1_1_1_, history0_.description as descript2_1_1_, history0_.eventId as eventId3_1_1_ from History history0_ where history0_.eventId=?
Event(id=1, description='event description', history=1)
=============2=============
Hibernate: select history0_.id as id1_1_0_, history0_.description as descript2_1_0_, history0_.eventId as eventId3_1_0_ from History history0_ where history0_.id=?
Hibernate: select event0_.id as id1_0_0_, event0_.description as descript2_0_0_ from Event event0_ where event0_.id=?
Hibernate: select history0_.eventId as eventId3_1_0_, history0_.id as id1_1_0_, history0_.id as id1_1_1_, history0_.description as descript2_1_1_, history0_.eventId as eventId3_1_1_ from History history0_ where history0_.eventId=?
History(id=1, event=Event(id=1, description='event description', history=1), description='history description')
Lazy initialisation start to load field data only after explicit getting a value.
Hope this will help you.
How do I set the parameter for the argument of the query below:
entity:
package net.bounceme.dur.usenet.model;
import java.io.Serializable;
import java.util.logging.Logger;
import javax.mail.Folder;
import javax.mail.Message;
import javax.persistence.*;
import net.bounceme.dur.usenet.driver.FetchBean;
#Entity
public class Article implements Serializable {
private static final long serialVersionUID = 1L;
private static final Logger LOG = Logger.getLogger(Article.class.getName());
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Column
private int messageNumber;
#ManyToOne(cascade = CascadeType.PERSIST)
private Newsgroup newsgroup;
public Article() {
}
public Article(Message message, Folder folder) {
messageNumber = message.getMessageNumber();
EntityManagerFactory emf;
EntityManager em;
emf = Persistence.createEntityManagerFactory("USENETPU");
em = emf.createEntityManager();
String ng = folder.getFullName();
Query query = em.createQuery("SELECT n FROM Newsgroup n WHERE n.newsgroup = :newsgroup", Newsgroup.class);
Newsgroup result = (Newsgroup) query.getSingleResult();
newsgroup = (result == null) ? new Newsgroup(folder) : result;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
#Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Article)) {
return false;
}
Article other = (Article) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
#Override
public String toString() {
return "\nmessageNumber\t" + messageNumber;
}
public int getMessageNumber() {
return messageNumber;
}
public void setMessageNumber(int messageNumber) {
this.messageNumber = messageNumber;
}
}
Stack trace:
run:
DEBUG: nntp: newsrc loading /home/thufir/.newsrc
DEBUG: nntp: newsrc load: 5 groups in 39ms
[EL Info]: 2012-08-03 03:26:30.737--ServerSession(13970219)--EclipseLink, version: Eclipse Persistence Services - 2.3.0.v20110604-r9504
[EL Info]: 2012-08-03 03:26:31.815--ServerSession(13970219)--file:/home/thufir/NetBeansProjects/USENET/build/classes/_USENETPU login successful
Aug 03, 2012 3:26:32 AM net.bounceme.dur.usenet.driver.FetchBean <init>
INFO: [gwene.com.androidcentral, gwene.com.blogspot.emacsworld, gwene.com.blogspot.googlecode, gwene.com.blogspot.googlereader, gwene.com.economist]
Aug 03, 2012 3:26:32 AM net.bounceme.dur.usenet.driver.FetchBean <init>
INFO: Google helping out newcomers with Nexus 7 getting started video
Aug 03, 2012 3:26:33 AM net.bounceme.dur.usenet.driver.FetchBean main
SEVERE: null
java.lang.IllegalStateException: Query argument newsgroup not found in the list of parameters provided during query execution.
at org.eclipse.persistence.internal.jpa.EJBQueryImpl.processParameters(EJBQueryImpl.java:829)
at org.eclipse.persistence.internal.jpa.EJBQueryImpl.executeReadQuery(EJBQueryImpl.java:406)
at org.eclipse.persistence.internal.jpa.EJBQueryImpl.getSingleResult(EJBQueryImpl.java:773)
at net.bounceme.dur.usenet.model.Article.<init>(Article.java:34)
at net.bounceme.dur.usenet.driver.FetchBean.<init>(FetchBean.java:41)
at net.bounceme.dur.usenet.driver.FetchBean.main(FetchBean.java:21)
BUILD SUCCESSFUL (total time: 13 seconds)
The named parameter should be ng, for newsgroup name, but I can't seem to get the syntax to query for that string in the Newsgroup.newsgroup field. How do I fix the query?
-------------EDIT----------------
new trace:
run:
DEBUG: nntp: newsrc loading /home/thufir/.newsrc
DEBUG: nntp: newsrc load: 5 groups in 30ms
[EL Info]: 2012-08-03 03:57:03.647--ServerSession(33288487)--EclipseLink, version: Eclipse Persistence Services - 2.3.0.v20110604-r9504
[EL Info]: 2012-08-03 03:57:04.691--ServerSession(33288487)--file:/home/thufir/NetBeansProjects/USENET/build/classes/_USENETPU login successful
Aug 03, 2012 3:57:05 AM net.bounceme.dur.usenet.driver.FetchBean <init>
INFO: [gwene.com.androidcentral, gwene.com.blogspot.emacsworld, gwene.com.blogspot.googlecode, gwene.com.blogspot.googlereader, gwene.com.economist]
Aug 03, 2012 3:57:05 AM net.bounceme.dur.usenet.driver.FetchBean <init>
INFO: Google helping out newcomers with Nexus 7 getting started video
Aug 03, 2012 3:57:06 AM net.bounceme.dur.usenet.driver.FetchBean main
SEVERE: null
java.lang.IllegalArgumentException: You have attempted to set a parameter value using a name of gwene.com.androidcentral that does not exist in the query string SELECT n FROM Newsgroup n WHERE n.newsgroup = :ng.
at org.eclipse.persistence.internal.jpa.EJBQueryImpl.setParameterInternal(EJBQueryImpl.java:1256)
at org.eclipse.persistence.internal.jpa.EJBQueryImpl.setParameter(EJBQueryImpl.java:1138)
at org.eclipse.persistence.internal.jpa.EJBQueryImpl.setParameter(EJBQueryImpl.java:81)
at net.bounceme.dur.usenet.model.Article.<init>(Article.java:34)
at net.bounceme.dur.usenet.driver.FetchBean.<init>(FetchBean.java:41)
at net.bounceme.dur.usenet.driver.FetchBean.main(FetchBean.java:21)
BUILD SUCCESSFUL (total time: 17 seconds)
code snippet:
String ng = folder.getFullName();
Query query = em.createQuery("SELECT n FROM Newsgroup n WHERE n.newsgroup = :ng", Newsgroup.class);
query.setParameter(ng, ng); //newsgroup object????
Newsgroup result = (Newsgroup) query.getSingleResult();
LOG.info(result.toString());
newsgroup = (result == null) ? new Newsgroup(folder) : result;
I'm playing around with it and will no doubt get it, just need to read the docs and API a bit more, but it's close enough :)
Query query = em.createQuery("SELECT n FROM Newsgroup n WHERE n.newsgroup = :newsgroup");
query.setParameter("newsgroup",newsgroup object);
Newsgroup result = (Newsgroup) query.getSingleResult();
Or you can use setString(..) method of the query:
Query query = em.createQuery("SELECT n FROM Newsgroup n WHERE n.newsgroup = :newsgroup", Newsgroup.class);
query.setString("newsgroup", ng);
Newsgroup result = (Newsgroup) query.getSingleResult();
For the record, the following runs:
public Article(Message message, Folder folder) {
messageNumber = message.getMessageNumber();
EntityManagerFactory emf;
EntityManager em;
emf = Persistence.createEntityManagerFactory("USENETPU");
em = emf.createEntityManager();
String ng = folder.getFullName();
TypedQuery<Newsgroup> query = em.createQuery("SELECT n FROM Newsgroup n WHERE n.newsgroup = :newsgroup", Newsgroup.class);
query.setParameter("newsgroup", ng);//newsgroup object
Newsgroup result = query.getSingleResult();
LOG.info(result.toString());
newsgroup = (result == null) ? new Newsgroup(folder) : result;
}
only with the minor error of:
run:
DEBUG: nntp: newsrc loading /home/thufir/.newsrc
DEBUG: nntp: newsrc load: 5 groups in 12ms
[EL Info]: 2012-08-03 04:21:28.427--ServerSession(18852961)--EclipseLink, version: Eclipse Persistence Services - 2.3.0.v20110604-r9504
[EL Info]: 2012-08-03 04:21:29.496--ServerSession(18852961)--file:/home/thufir/NetBeansProjects/USENET/build/classes/_USENETPU login successful
Aug 03, 2012 4:21:30 AM net.bounceme.dur.usenet.driver.FetchBean <init>
INFO: [gwene.com.androidcentral, gwene.com.blogspot.emacsworld, gwene.com.blogspot.googlecode, gwene.com.blogspot.googlereader, gwene.com.economist]
Aug 03, 2012 4:21:30 AM net.bounceme.dur.usenet.driver.FetchBean <init>
INFO: Google helping out newcomers with Nexus 7 getting started video
Aug 03, 2012 4:21:31 AM net.bounceme.dur.usenet.driver.FetchBean main
SEVERE: null
javax.persistence.NoResultException: getSingleResult() did not retrieve any entities.
at org.eclipse.persistence.internal.jpa.EJBQueryImpl.throwNoResultException(EJBQueryImpl.java:1310)
at org.eclipse.persistence.internal.jpa.EJBQueryImpl.getSingleResult(EJBQueryImpl.java:778)
at net.bounceme.dur.usenet.model.Article.<init>(Article.java:35)
at net.bounceme.dur.usenet.driver.FetchBean.<init>(FetchBean.java:41)
at net.bounceme.dur.usenet.driver.FetchBean.main(FetchBean.java:21)
BUILD SUCCESSFUL (total time: 14 seconds)
I found the tutorial not terribly helpful, but at least fixed that syntax problem, I think.
I've a problem using Hibernate, after executing one of my queries I get the following Log messages and the program stops to work:
20:36:48,805 TRACE ThreadLocalSessionContext:344 - allowing proxied method [createQuery] to proceed to real session
4608 [main] TRACE org.hibernate.context.ThreadLocalSessionContext - allowing proxied method [createQuery] to proceed to real session
20:36:48,806 TRACE QueryPlanCache:128 - located HQL query plan in cache (from Propertylist where typedlistId = ?)
4609 [main] TRACE org.hibernate.engine.query.QueryPlanCache - located HQL query plan in cache (from Propertylist where typedlistId = ?)
In practice I have a small method where I call:
public List<Zielobjekt> gibZielobjekte() {
List<Zielobjekt> zielobjekte = new ArrayList<Zielobjekt>();
Session session = _sessionFactory.getCurrentSession();
session.beginTransaction();
for(Informationsverbund iv : gibInformationsverbuende() /*Behind this method is a Hibernate query, it works fine.*/ )
{
Set<Celement> zobjekte = gibBaumelementeFuerVater(session, iv.getOriginalId());
LOGGER.info("Insgesamt " + zobjekte.size() + " ZO gefunden.");
for(Celement element : zobjekte)
{
Set<Propertylist> eigenschaften = gibEigenschaftsliste(session, element); /*Behind this Method is a Hibernate Query, here the Program stops to work.*/
//HERE THE PROGRAM STOPS WORKING
...
}
}
session.getTransaction().commit();
return zielobjekte;
}
The method called, where the program stops working is:
private Set<Propertylist> gibEigenschaftsliste(Session session, Celement element)
{
try
{
return new HashSet(session.createQuery(
"from Propertylist where typedlistId = ?")
.setInteger(0, element.getEntityId())
.list());
}
catch (HibernateException e)
{
e.printStackTrace();
return null;
}
}