#OneToMany relationship property not filled - jpa

I have implemented Joined, Multiple Table Inheritance.
There is a 'parent' table pois and two sub tables: xPois and yPois and in turn I have an abstract PoiDao class as well as a XPoiDao and a YPoiDao class extending PoiDao.
A poi may have multiple reservations but a reservation belongs to exactly one poi.
Named queries defined in the child table DAOs work well for attributes defined in the respective (direct) table hierarchy. The parent table has a foreign key relationship to another table named reservations (table reservations holds the foreign key of table pois). The problem is that the records from this reservations table get not fetched.
Running this SQL statement in MySql Workbench gets the desired resultset:
SELECT * FROM xPois pp
LEFT JOIN pois p ON pp.poiId = p.poiId
LEFT JOIN reservations r ON p.poiId = r.poiId
WHERE pp.xPoiId = '2011';
In Eclipse I can see {IndirectList: not instantiated} when I inspect the xDao instance in debug mode.
How can I get the records from this table being stored in the PoiDao using JPA?
public abstract class PoiDao implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="poiId")
private Integer poiId;
#OneToOne(optional=false, cascade=CascadeType.ALL)
#JoinColumn(name="addressId",insertable=true,
updatable=true, unique=true, nullable=false)
private AddressDao address;
#Embedded
private GeoLocationDao geoLocation;
#Convert("poiTypeConverter")
private ServiceTypeEnum poiType;
#Column(name="operator")
private String operator;
#Column(name="reservable")
private boolean reservable;
#OneToMany(orphanRemoval=true, cascade=CascadeType.ALL, fetch=FetchType.LAZY)
#JoinColumn(name="poiId", insertable=true, updatable=true)
private List<ReservationDao> existingReservations;
...
}
#Entity
#Table(name="xPois")
#DiscriminatorValue("X")
#NamedQueries({
#NamedQuery(name="XPoiDao.findAll", query="SELECT p FROM XPoiDao p"),
#NamedQuery(name="XPoiDao.findByXPoiId",
query="SELECT pp FROM XPoiDao pp LEFT JOIN PoiDao p ON pp.poiId = p.poiId "
+ "LEFT JOIN ReservationDao r ON p.poiId = r.poiId WHERE pp.xPoiId = :xPoiId")
})
#ObjectTypeConverters({
#ObjectTypeConverter (
name="xPoiStatusConverter",
dataType=java.lang.String.class, // type in DB
objectType=XPoiStatusEnum.class, // Java type
conversionValues={
#ConversionValue(dataValue="FREE", objectValue="FREE"),
#ConversionValue(dataValue="OCCUPIED BY VALUE", objectValue="OCCUPIED_BY_VALUE"),
#ConversionValue(dataValue="OCCUPIED MANUALLY", objectValue="OCCUPIED_MANUALLY"),
#ConversionValue(dataValue="BLOCKED", objectValue="BLOCKED")
}
)
})
public class XPoiDao extends PoiDao implements Serializable {
/**
*
*/
private static final long serialVersionUID = 2496267921294255723L;
// #Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="id")
private Integer id;
#Column(name="xPoiId")
private String xPoiId;
#Convert("xPoiStatusConverter")
#Column(name="status")
private XPoiStatusEnum status;
#Embedded
private ContactDao contact;
// #OneToMany(orphanRemoval=true, cascade=CascadeType.ALL, fetch=FetchType.LAZY)
// #JoinColumn(name="poiId",insertable=true,updatable=true)
// private List<ReservationDao> existingReservations;
#OneToMany(orphanRemoval=true, cascade=CascadeType.ALL, fetch=FetchType.LAZY)
#JoinColumn(name="parkingPoiId",insertable=true,updatable=true)
private List<OperatingHourDao> operatingHours;
...
}

You've got FetchType.LAZY in there. Do you get an empty list when you try to access it? Debuggers might not trigger the fetch requests.

Related

Spring data jpa JOIN does't work in #Query

I am using spring-data-jpa. I wrote a native query but it doesn't work. Here is my entity classes:
#Entity
#Table(name="view_version")
public class ViewVersionDom {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private Long id;
#ManyToOne
#JoinColumn(name="view_id")
private ViewDom view;
private Integer version;
#ManyToOne
#JoinColumn(name="datasource_param_id")
private DatasourceParamDom datasourceParam;
private String description;
#Column(name="created_date")
private Date createdDate;
#Entity
#Table(name="view_permission")
public class ViewPermissionDom extends BaseDom {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private Long id;
#ManyToOne
#JoinColumn(name="view_id")
private ViewDom view;
#ManyToOne
#JoinColumn(name="user_id")
private UserDom user;
#ManyToOne
#JoinColumn(name="group_id")
private GroupDom group;
private Boolean read;
private Boolean write;
private Boolean execute;
Here is the query:
#Query(value = " SELECT v FROM ViewVersionDom v LEFT JOIN ViewPermissionDom vp ON v.view.id = vp.id "
+ " where (v.view.user.id = ?1 OR (vp.read=true and (vp.user.id=?1 or vp.user.id is NULL and vp.group.id is NULL or vp.group.id in (?2)))) "
+ " ORDER BY v.view.name", nativeQuery=true)
public List<ViewVersionDom> findUserViews(Long userId, List<Long> groupIds);
At first when I didn't write nativeQuery=true the application didn't build and I got an exception 'path expected for join jpa'. When I set the settings nativeQuery=true the application is started, but when I call the function I got the following error:
org.hibernate.engine.jdbc.spi.SqlExceptionHelper - [ERROR: relation "viewversiondom" does not exist Position: 16]
org.hibernate.exception.SQLGrammarException: could not extract ResultSet]
Does there any other settings or annotation that will resolve the problem?
I have searched in google, but in all cases 2 tables connected with each other directly.
Your query is not a SQL query (assuming, you don't have a column v in one for your tables).
Also the Table viewversiondom doesn't exist or is not accessible to the database user used for the connection.
Also when mapping native queries to domain objects you should have a look at https://jira.spring.io/browse/DATAJPA-980

Hibernate Postgresql select for update with outer join issue

I have faced with issue trying to select for update row using Spring data with Hibernate as JPA implementation and Postgresql.
Suppose we have entities:A,B,C.
public class A{
#Id
private Long id;
#OneToMany(fetch = FetchType.EAGER)
private Set<B> bSet;
#OneToMany(fetch = FetchType.EAGER)
private Set<C> cSet;
}
Suppose we want to select A with all related B and C entities for update i.e. with locking row related to A table.
#Query(SELECT a FROM A a
LEFT JOIN FETCH a.bSet
LEFT JOIN FETCH a.cSet
WHERE a.id=?)
#Lock(LockModeType.PESSIMISTIC_WRITE)
public A selectAndLockA(Long Aid);
The query will look like
SELECT a.column1, ... from tableA a LEFT JOIN tableB b ... FOR UPDATE of a,c
FOR UPDATE of a,c
The query will try to lock two tables what leads to exception like :
org.postgresql.util.PSQLException: ERROR: FOR UPDATE cannot be applied to the nullable side of an outer join
What I try to archive is locking only first table "FOR UPDATE OF a"
Is it possible to configure somehow or tell Hibernate to lock only first table.
This is not supported by PostreSQL. If you do an outer SELECT nothing can prevent somebody from inserting a row into the LEFT JOINED table thereby modifiying the result set you are looking at (e.g. the columns would not be NULL anymore on a repeated read).
For a detailed explanantion see here
It's been a long time since question was created, but I have a similar problem and hope my answer will help somebody.
Suppose that we have this JPA entities:
#Entity
#Table(name = "card_transactions")
public class CardTransactionsEntity {
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "card_trans_seq")
#SequenceGenerator(name = "card_trans_seq", sequenceName = "card_trans_seq")
private Long id;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumns({
#JoinColumn(name = "ofd_id", referencedColumnName = "ofd_id"),
#JoinColumn(name = "receipt_id", referencedColumnName = "receipt_id")})
private ReceiptsEntity receipt;
#Column
#Enumerated(EnumType.STRING)
private CardTransactionStatus requestStatus;
...
}
#Entity
#Table(name = "receipts")
public class ReceiptsEntity {
#EmbeddedId
private OfdReceiptId id;
...
}
#Embeddable
public class OfdReceiptId implements Serializable {
#Column(name = "ofd_id")
#Enumerated(EnumType.STRING)
private OfdId ofdId;
#Column(name = "receipt_id")
private String receiptId;
...
}
And we want select CardTransactionsEntity with fetched ReceiptsEntity for pessimistic update only CardTransactionsEntity. This can be done using Hibernate and Spring Data JPA repository as
public interface CardTransactionRepository extends JpaRepository<CardTransactionsEntity, Long> {
#Query("select ct from CardTransactionsEntity ct left join fetch ct.receipt r where ct.requestStatus = :requestStatus")
#Lock(value = LockModeType.PESSIMISTIC_WRITE)
#QueryHints(value = {
#QueryHint(name = "javax.persistence.lock.timeout", value = "-2"), // LockOptions.SKIP_LOCKED
#QueryHint(name = "org.hibernate.lockMode.r", value = "NONE") // "r" is alias for ct.receipt and will excluded from PESSIMISTIC_WRITE
})
List<CardTransactionsEntity> loadCardTransactions(#Param("requestStatus") CardTransactionStatus requestStatus, Pageable pageable);
}
This repository method will execute query like
SELECT ct.*, r.* from card_transactions ct LEFT OUTER JOIN receipts r ON ct.ofd_id = r.ofd_id and ct.receipt_id = r.receipt_id WHERE ct.request_status=? LIMIT ? FOR UPDATE OF ct SKIP LOCKED
You can bypass this error with joining the tables with FetchType.LAZY. This fetch type is the default one and it is not required to specify for #OneToMany joins.
public class A{
#Id
private Long id;
#OneToMany
private Set<B> bSet;
#OneToMany
private Set<C> cSet;
}

Joining two table entities with #OneToOne annotation generate "cross join" while "inner join" expected

I have OneToOne tables/entities Person and Employee:
each employee has only one person and each person is attached to one and only one employee.
The generated query do tables join with "cross join" keyword while "inner join" would be more appropriate
#Entity
#Table(name="person")
#Data
public class Person implements Serializable {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="id_Person", unique=true, nullable=false)
private long id;
#Column(nullable=false, length=50)
private String name;
#Column(nullable=false, length=255)
private String EMail;
}
#Entity
#Table(name="employee")
#Data
public class Employee implements Serializable {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="id_Employee", unique=true, nullable=false)
private long id;
#Column(nullable=false, length=50)
private String numero;
#OneToOne(fetch = FetchType.EAGER, optional=false)
#JoinColumn(name="id_Employee")
private Person person;
}
Repository:
public interface EmployeeRepository extends CrudRepository {
#Query("SELECT e FROM Employee e WHERE LOWER(e.person.name) LIKE CONCAT(LOWER(:name),'%')")
List findByName(#Param("name") String name);
}
Here is thes generated queries:
select employee0_.id_Employee as id_Emplo1_0_, employee0_.department as departme2_0_
from employee employee0_
cross join person person1_
where employee0_.id_Employee=person1_.id_Person
and (lower(person1_.name) like concat(lower(?), '%'))
;
select person0_.id_Person as id_Perso1_2_0_, person0_.EMail as EMail2_2_0_, person0_.name as name3_2_0_
from person person0_
where person0_.id_Person=?
;
You have an error in the entity Employee, join column should be id_Person.
Apart from that, I'd recommend using Querydsl for a fine-grained control over your joins. Your query will look something like this:
query.from(employee).leftJoin(employee.person, person)
.where(person.name.lower().like(name.toLowerCase() + "%")).fetch();

JPA CRITERIA QUERY with order by joined columns

How to invoke order by on a joined entity? I am trying to achieve the following with:
select * from person p inner join telephone t on p.id=t.person_id join sim s on s.id=t.sim_id order by s.name DESC
#Entity
public class Person implements Serializable{
#Id
private Long id;
#OneToMany(orphanRemoval = true, mappedBy = "person", fetch = FetchType.LAZY, cascade = CascadeType.PERSIST)
private List<Telephone> telephonesNumber;
#Entity
public class Telephone implements Serializable {
#Id
private String number;
#Id
#ManyToOne()
#JoinColumn(name = "person_id")
private Person person;
#Id
#ManyToOne(cascade = {})
#JoinColumn(name = "sim_id")
private Sim sim;
#Entity
public class Sim implements Serializable {
#Id
private Long id;
#Column(unique = true)
private String name;
I use specification interface, in this example sorting is on the field person.id and it works
public class PersonSpecification implements Specification<Person> {
#Override
public Predicate toPredicate(Root<Person> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
List<Predicate> predicates = new ArrayList<>();
// there is many different conditions for example
// if(someCondition!=null) {
// predicates.add(builder.like(root.get("someProperty"), someValue));
// }
query.groupBy(root.get("id"));
//there I want to order by Sim.name i dont know how
query.orderBy(builder.asc(root.get("phone")));//this works
return builder.and((predicates.toArray(new Predicate[predicates.size()])));
}
I want to order by Sim.name but i dont know how.
In JPA specification you can use:
query.orderBy(builder.asc(root.join("telephonesNumber").get("sim").get("name")));
to sort by sim name.
For more details:
https://en.wikibooks.org/wiki/Java_Persistence/Querying#Joining.2C_querying_on_a_OneToMany_relationship
If you using JPA Query:
#Query("select s from Person p
join p.telephonesNumber t
join t.sim s order
by t.sim.id desc")
It will produce this:
select * from person p
inner join telephone t on p.id=t.person_id
inner join sim s on t.sim_id=s.id
order by t.sim_id desc
For more details:
https://github.com/abhilekhsingh041992/spring-boot-samples/blob/master/jpa/src/main/java/example/springboot/jpa/repository/PersonRepository.java
another way for that would be using Query method:
List<Telephone> findAllByOrderBySimIdAsc();
Look at this findAllByOrderBySimIdAsc
With the code before, you can get all rows from Telephone ordered by Sim Id.

JPA Error joining table and view

I need to join a table and a view in a JPA query. The query won't compile because the view columns can't be identified.
Any suggestions are greatly appreciated.
Updated with parent entity and consistent naming
The query is:
select count(m.id)
from MultiSpeedMotor m,
MultiSpeedQuery q1
where m.id = q1.motorId
and q1.power = 10
The errors are:
The state field path 'q1.motorId' cannot be resolved to a valid type.
The state field path 'q1.power' cannot be resolved to a valid type.
I am working with a legacy database that has a denormalized table similar to this
Long motorId
Long id
Double hi_power
Double lo_power
I have used a view with a union query to normalize this table into
Long motorId
Long id
Long hi
Double power
To model the view of union query in JPA, I have used an #IdClass
public class MultiSpeedQueryId implements Serializable {
private static final long serialVersionUID = -7996931190943239257L;
private Long motorId;
private Long id;
private Long hi;
...
}
#Entity
#Table(name = "multi_speed_query")
#IdClass(MultiSpeedQueryId.class)
public class MultiSpeedQuery implements IMultiSpeedQuery {
#Id
#Column(name = "motor_id")
private Long motorId;
#Id
private Long id;
#Id
private Long hi;
private Double power;
...
}
The parent Entity is mapped as:
#Entity
#Table(name = "multi_speed_motor")
public class MultiSpeedMotor implements Serializable, IMultiSpeedMotor {
private static final long serialVersionUID = 3019928176257499187L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
...
}
The query is correct as written.
You CAN join Entities with no pre-defined relationship by using the syntax.
where a.id = b.joinField
The issue was much simpler. I missed part of the JPA error log that was telling the real problem.
The abstract schema type 'MultiSpeedQuery' is unknown.
Once I added the Entity to the persistence.xml, the query, as originally written, worked perfectly.