not quite understanding lazy-loading - jpa

I have a situation where lazy-loading is not occurring when I want it to in a one-to-many.
Obviously, I am new to this. Why won't the SongComposers get fetched when I call s.getSongComposers()?
Here is my DAO class:
public class SongDAOImpl implements SongDAO {
#PersistenceContext
private EntityManager em;
#Override
#SuppressWarnings(value = { "unchecked" })
public List<Song> getAllSongsOnAlbum(int albumID) {
Query q = em.createQuery("SELECT s FROM Song s WHERE s.album.albumID = :albumid ORDER BY s.songName");
q.setParameter("albumid", albumID);
List<Song> list = (List<Song>) q.getResultList();
for (Song s: list) {
s.getSongComposers();
}
return list;
}
}
Here is my Song entity:
#Entity
#Table(name="songs")
public class Song {
#Id
#GeneratedValue
#Column(name="SongID")
private int songID;
#Column(name="SongName")
private String songName;
#Column(name="Length")
private int length;
#ManyToOne
#JoinColumn(name="AlbumID", referencedColumnName="AlbumID")
private Album album;
#OneToMany(mappedBy="song")
private List<SongComposer> songComposers;
.... all getters/setters ......
}
Here is my SongComposer entity:
#Entity
#Table(name="song_composer")
public class SongComposer {
#Id
#GeneratedValue
#Column(name="SongComposerID")
private int songComposerID;
#ManyToOne
#JoinColumn(name="SongID", referencedColumnName="SongID")
private Song song;
#ManyToOne
#JoinColumn(name="ComposerID", referencedColumnName="ComposerID")
private Composer composer;
..... getters/setters .......
}

You have to do it explicitly. Try this query:
SELECT DISTINCT s FROM Song s JOIN FETCH s.songComposers WHERE s.album.albumID = :albumid ORDER BY s.songName"

Related

Spring Data JPA #OneToOne mapping is not projected

This question is already phrased as an issue here: https://github.com/spring-projects/spring-data-jpa/issues/2369 but for lack of a reaction there I am copying the contents of that issue here, hoping that somebody might find what's wrong with my code or confirm that this could be a bug:
I've set up an example project here that showcases what seems to be a bug in Spring Data projections: https://github.com/joheb-mohemian/gs-accessing-data-jpa/tree/primary-key-join-column-projection-bug/complete
I have a Customer entity that has a OneToOne mapping to an Address entity:
#Entity
public class Customer {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private Long id;
private String firstName;
private String lastName;
#OneToOne(mappedBy = "customer", cascade = CascadeType.ALL)
#PrimaryKeyJoinColumn
private Address address;
//...
}
#Entity
public class Address {
#Id
#Column(name = "customer_id")
private Long id;
#OneToOne
#MapsId
#JoinColumn(name = "customer_id")
private Customer customer;
private String street;
//...
}
Then there are simple projection interfaces:
public interface CustomerProjection {
String getFirstName();
String getLastName();
AddressProjection getAddress();
}
public interface AddressProjection {
String getStreet();
}
But when I try to fetch a projected entity from a repository method like this one:
public interface CustomerRepository extends CrudRepository<Customer, Long> {
//...
<T> T findById(long id, Class<T> type);
}
, getAddress() on the projection will be null, whereas getAddress() when fetching the entity type is populated correctly. Of these two unit tests, only testEntityWithOneToOne()will be successful:
#BeforeEach
void setUpData() {
customer = new Customer("first", "last");
Address address = new Address(customer, "street");
customer.setAddress(address);
entityManager.persist(address);
entityManager.persist(customer);
}
#Test
void testEntityWithOneToOne() {
Customer customerEntity = customers.findById(customer.getId().longValue());
assertThat(customerEntity.getAddress()).isNotNull();
}
#Test
void testProjectionWithOneToOne() {
CustomerProjection customerProjection = customers.findById(customer.getId(), CustomerProjection.class);
assertThat(customerProjection.getAddress()).isNotNull();
}
What's the problem here?

Get container entity using child id

I want to get the branch object in which leaf(using it's ID) belongs to
What is the right approach to get the branch given that I only have the leaf ID? I thought of looping through all the branches in the db and get the one which contain the leaf ID which looks bad
#Entity
public class Branch {
#Id
#GeneratedValue
Long id;
#OneToMany
#JoinColumn(name = "branch_id")
private List<Leaf> leaves
}
#Entity
public class Leaf {
#Id
#GeneratedValue
Long id;
private String name;
}
#Service
public class BranchService {
private final BranchRepository branchRepository;
#Autowired
public BranchService(BranchRepository branchRepository) {
branchRepository = branchRepository;
}
public Tree getBranchByLeaf(Long leafId){
// ??
}
}
Try something like this:
public interface BranchRepository extends JpaRepository<Branch, Long> {
#Query("select b from Branch b join b.leaves l where l.id = ?1")
List<Branch> getByLeafId(Long leafId);
}
#Service
public class BranchService {
private final BranchRepository branchRepository;
#Autowired
public BranchService(BranchRepository branchRepository) {
branchRepository = branchRepository;
}
public List<Branch> getByLeafId(Long leafId){
return branchRepository.getByLeafId(Long leafId);
}
}

There is no ID defined for this entity hierarchy

I am stuck with this error message, that appears every time I want to add a ManytoOne relationship with another entity class.
The class must use a consistent access type (either field or property). There is no ID defined for this entity hierarchy
This is my entity Transaction
#Entity
#Table(name = "CustomerTransaction")
public class CustomerTransaction implements Serializable {//this is the line with the error message
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#ManyToOne //This generates the problem
#JoinColumns({
#JoinColumn(name = "CUS_ID", referencedColumnName = "IDCUSTOMER") })
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
private long transactionID;
#Temporal(TemporalType.TIMESTAMP)
private Date buyDate;
public Date getBuyDate() {
return buyDate;
}
public void setBuyDate(Date buyDate) {
this.buyDate = buyDate;
}
public long getTransactionID() {
return transactionID;
}
public void setTransactionID(long transactionID) {
this.transactionID = transactionID;
}
public String getCarYear() {
return carYear;
}
public void setCarYear(String carYear) {
this.carYear = carYear;
}
public Date getTransactionDate() {
return transactionDate;
}
public void setTransactionDate(Date transactionDate) {
this.transactionDate = transactionDate;
}
private String carYear;
#Temporal(TemporalType.TIMESTAMP)
private Date transactionDate;
JPA annotation should all be placed either on fields or on accessor methods. You've placed the #Id and #GeneratedValue annotation on a field (private Long id), but #ManyToOne and #JoinColumns on a getter (public Long getId()). Move the latter on a field as well.
i had similar error but in the end, i realized #Id was referencing this package org.springframework.data.annotation.Id instead of javax.persistence.Id. i was using #MappedSuperClass approach so as soon as i corrected this, everything worked fine
You need to import #Id from "import javax.persistence.Id;"

fetch one to many side with jpql

so I have done two entities with one to many relationship,
I have one category whohas many visitors,
and this is my code:
this is the Category entity :
#Entity
public class Category implements Serializable {
private Integer id;
private String name;
private List<Visitor> visitors = new ArrayList<Visitor>();
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#OneToMany(cascade=CascadeType.REMOVE, fetch = FetchType.LAZY, mappedBy = "category", orphanRemoval = true)
public List<Visitor> getVisitors() {
return visitors;
}
public void setVisitors(List<Visitor> visitors) {
this.visitors = visitors;
}
}
and here is the Visitor Entity :
#Entity
public class Visitor extends User {
private String passport;
private String citizenship;
private String gender;
private Company company;
private Category category;
public String getPassport() {
return passport;
}
public void setPassport(String passport) {
this.passport = passport;
}
public String getCitizenship() {
return citizenship;
}
public void setCitizenship(String citizenship) {
this.citizenship = citizenship;
}
#ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
public Category getCategory() {
return category;
}
public void setCategory(Category category) {
this.category = category;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
#ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
public Company getCompany() {
return company;
}
public void setCompany(Company company) {
this.company = company;
}
and here is the service method who list all the visitors and works fine :
public List<Visitor> findAllVisitors() {
return em.createQuery(
"SELECT v from Visitor v left join fetch v.category",
Visitor.class).getResultList();
}
with this method I can list all the visitors each with his category object associated,
now the problem is in the other side of the relationship ,
here is the method who list the categories each with their visitors list :
public List<Category> findAllCategories() {
return em.createQuery("select c from Category c",
Category.class).getResultList();
}
I want to get the list of all the categories but when I call this method in a REST call , I get this result :
I want just to get a simple list of categories (id and name).
what is wrong in my code please help me i am confused.
UPDATE:
this is how I get JSON from persistence context with RESTful method :
#Inject
private CategoryServiceLocal categoryServiceLocal;
#GET
#Produces(MediaType.APPLICATION_JSON)
public List<Category> dofindAllCategories() {
return categoryServiceLocal.findAllCategories();
}
You have a lazy association from Category to visitors. To load all visitors you need to use left join fetch too.
select c from Category c left join fetch c.visitors
Please, use additional annotations to control how to JSON generated
Infinite Recursion with Jackson JSON and Hibernate JPA issue

How to correctly do a manytomany join table in JPA?

I need 3 entities: User, Contract (which are a many to many relation) and a middle entity: UserContract (this is needed to store some fields).
What I want to know is the correct way to define the relationships between these entities in JPA/EJB 3.0 so that the operations (persist, delete, etc) are OK.
For example, I want to create a User and its contracts and persist them in a easy way.
Currently what I have is this:
In User.java:
#OneToMany(mappedBy = "user", fetch = FetchType.LAZY)
private List<UserContract> userContract;
In Contract.java:
#OneToMany(mappedBy = "contract", fetch = FetchType.LAZY)
private Collection<UserContract> userContract;
And my UserContract.java:
#Entity
public class UserContract {
#EmbeddedId
private UserContractPK userContractPK;
#ManyToOne(optional = false)
private User user;
#ManyToOne(optional = false)
private Contract contract;
And my UserContractPK:
#Embeddable
public class UserContractPK implements Serializable {
#Column(nullable = false)
private long idContract;
#Column(nullable = false)
private String email;
Is this the best way to achieve my goals?
Everything looks right. My advice is to use #MappedSuperclass on top of #EmbeddedId:
#MappedSuperclass
public abstract class ModelBaseRelationship implements Serializable {
#Embeddable
public static class Id implements Serializable {
public Long entityId1;
public Long entityId2;
#Column(name = "ENTITY1_ID")
public Long getEntityId1() {
return entityId1;
}
#Column(name = "ENTITY2_ID")
public Long getEntityId2() {
return entityId2;
}
public Id() {
}
public Id(Long entityId1, Long entityId2) {
this.entityId1 = entityId1;
this.entityId2 = entityId2;
}
}
protected Id id = new Id();
#EmbeddedId
public Id getId() {
return id;
}
protected void setId(Id theId) {
id = theId;
}
}
I omitted obvious constructors/setters for readability. Then you can define UserContract as
#Entity
#AttributeOverrides( {
#AttributeOverride(name = "entityId1", column = #Column(name = "user_id")),
#AttributeOverride(name = "entityId2", column = #Column(name = "contract_id"))
})
public class UserContract extends ModelBaseRelationship {
That way you can share primary key implementation for other many-to-many join entities like UserContract.