简体   繁体   中英

Custom Select for hibernate/JPA

I'm using JPA over Hibernate, with an annotation configuration.

I'm looking for doing a custom "select", that would allow me to know the size of a "lazy collection", without getting the collection.

I tried this, without success:

@Entity
@Table(name="t_test")   
public class Test {

@Id
@Column(name="name", length=50)
private String name;

@Column(name="first_name", length=50)
private String firstName;

@ElementCollection(fetch=FetchType.LAZY)
@JoinTable(name = "tj_test_nicknames", schema="",
    joinColumns = {@JoinColumn(name = "name")} 
)
@ForeignKey(name = "FK_test_nickname")
@Column(name="nickname", nullable=false)
private Set<String> nickNames = new HashSet();

@Formula("(SELECT COUNT(t.nickname) FROM tj_test_nicknames t WHERE t.name = name)")
private int counter;

In my test, i'm just trying to display the counter number ( with a classic for )

Test test = new Test();
test.setFirstName("prenom");
test.setName("nom" + Math.random());

Set<String> nickNames = new HashSet<String>();
nickNames.add("surnom");
nickNames.add("toto");
test.setNickNames(nickNames);

testDAO.save(test);

Collection<Test> tests = testDAO.getAll();
if(tests!=null){
    for (Test testT : tests) {
        logger.info("Number of nicknames: " + testT.getNumberOfNicknames());
        logger.info("Size of the list:: " + testT.getNickNames().size());
    }
}

But i display 0 for each object instance ( that has instanciated lazy collection ).

org.hibernate.pretty.Printer listing entities:...

Test{counter=2, name=nom0.46579385535806883, firstName=prenom, nickNames=}

Test{counter=0, name=nom0.6489676574372193, firstName=prenom, nickNames=[toto, surnom]}

Test{counter=2, name=nom0.6362777689140984, firstName=prenom, nickNames=}

Test{counter=2, name=nom0.15039481770844532, firstName=prenom, nickNames=}

Test{counter=2, name=nom0.5580054662200352, firstName=prenom, nickNames=}

EDIT: So i've understood that it's when the lazy collection nickNames is instanciated that it returns 0 and not the good number.

So it's really annoying, as i want to get the size in order not to intanciate the collection, but in the case i have the collection instanciated i must have a good information...

Anyone have an idea how to do it ?

Thanks,

The query should look like (there should not be any table keyword):

( (Integer) session.createQuery("select count(*) from ....").iterate().next() ).intValue();

Its from hibernate documentation

无论如何,您的查询看起来有点奇怪:我认为ID是您的主键,因此请计算id = XYZ的值仅返回0或1。-也许问题出在您的查询上。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM