Hibernate not fetching subentity if distinct not present - java

We have the following domain:
Members and Channels.
Member - equivalent of a user.
#Entity
#Table(name = "member")
public class Member {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Column(name = "first_name")
private String firstName;
}
Channel - Will group blog posts by topic.
#Entity
#Table(name = "channel")
public class Channel {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private Long id;
#Column(name = "name")
private String name;
}
The members can be assigned to channels thus becoming members in the channel. So we have the ChannelMember entity since we don't always want to retrieve both ends of the relationship.
#Entity
#Table(name = "channel_member")
public class ChannelMember {
#Id
#Column(name = "id")
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#OneToOne
#JoinColumn(name = "channel_id", nullable = false)
private Channel channel;
#OneToOne
#JoinColumn(name = "member_id", nullable = false)
private Member member;
}
We use Spring Data JPA and MySQL for our persistance(Spring Boot 1.5.3 Release).
Why is the distinct mandatory in the JPQL query for Hibernate to be able to fetch any records in the following case?
Repository code example as follows:
#Repository
public interface MemberRepository extends JpaRepository<Member, Long> {
#Query("select cm.member from ChannelMember cm")
List<Member> getNotWorking(); // empty List will be returned
#Query("select distinct cm.member from ChannelMember cm")
List<Member> getWorking();
}

Related

One table has two same joins in another table

I have one table called image and another table called duplicate. There are two OneToMany relations are associated.
I am not quite sure whether below implementation is the right approach for that. Moreover whether we require that second private List<DuplicateEntity> duplicateEntities2; ?
ImageEntity:
#Entity
#Table(name = "image")
public class ImageEntity {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Column(name = "filename")
private String fileName;
#OneToMany(mappedBy = "imageEntity1")
private List<DuplicateEntity> duplicateEntities1;
#OneToMany(mappedBy = "imageEntity2")
private List<DuplicateEntity> duplicateEntities2;
}
DuplicateEntity:
#Entity
#Table(name = "duplicate")
public class DuplicateEntity {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#ManyToOne
#JoinColumn(name = "image_a_id")
private ImageEntity imageEntity1;
#ManyToOne
#JoinColumn(name = "image_b_id")
private ImageEntity imageEntity2;
}

Spring CrudRepository - 'not equals' condition for child table(which is as List)

I've two entity with #OneToMany relationship
First Entity
#Entity
#Table(name = SchemaConstant.RESCHEDULE_TABLE_NAME)
public class RescheduleRequestEntity extends BaseEntity {
#Id
#GeneratedValue(strategy = GenerationType.AUTO, generator = "RESCHEDULE_ID_GEN")
#SequenceGenerator(
name = "RESCHEDULE_ID_GEN",
allocationSize = 1,
sequenceName = SchemaConstant.RESCHEDULE_SEQUENCE_NAME)
private Long id;
private String adviseNo;
private LocalDate adviseDate;
private Long customerId;
#Enumerated(value = EnumType.STRING)
private AdviceStatus status;
#OneToMany(mappedBy = "reschedule", fetch = FetchType.LAZY)
private List<RescheduleDetailEntity> accountDetails;
}
Second Entity
#Entity
#Table(name = "RESCHEDULE_DETAILS")
public class RescheduleDetailEntity extends BaseEntity {
#Id
#GeneratedValue(strategy = GenerationType.AUTO, generator = "RESCHEDULE_DETAILS_ID_GEN")
#SequenceGenerator(
name = "RESCHEDULE_DETAILS_ID_GEN",
allocationSize = 1,
sequenceName = "S_RESCHEDULE_DETAILS")
private Long id;
#OneToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "ACCOUNT_ID", nullable = false)
private AccountEntity account;
#Enumerated(value = EnumType.STRING)
private AdviceStatus status;
#Enumerated(value = EnumType.STRING)
private TenureType tenureType;
private Integer tenure;
#ManyToOne
#JoinColumn(name = "ADVISE_ID")
private RescheduleDetailEntity reschedule;
}
AND Enum
public enum AdviceStatus {
OPEN,
ACTIVE,
CLOSE
}
I want to fetch data with condition Like
SELECT *
FROM RESCHEDULEREQUESTENTITY R, RESCHEDULEDETAILENTITY D
WHERE R.ID = :PID
AND D.ADVISEID = R.ID
AND D.STATUS <> "CLOSE"
"Data fetch from RescheduleRequestEntity with data from RescheduleDetailEntity where RescheduleDetailEntity.status is not equal "CLOSE" where "Status" is Enum type".
I create a JPA Repository class like following for fetch data
#Repository
public interface RescheduleRequestRepository
extends JpaRepository<RescheduleRequestEntity, Long>, JpaSpecificationExecutor {
Optional<RescheduleRequestEntity> findByAdviseNo(String adviceNo);
Optional<RescheduleDetailEntity> findByIdAndAccountDetails_StatusNot(
Long adviceId, AdviceStatus status);
}
but it's not fetch data with my desired condition,it's not ignore data which have Status "CLOSE"
You can make it a custom query using #Query annotation.

How to persist objects and its nested objects at once?

I'm with some problems trying to persist an object and its items, here're my classes:
#Entity(name = "Contract")
#Table(name = "contract")
public class Contract implements Serializable{
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(unique = true, nullable = false)
private Long id;
#OneToMany(mappedBy = "idContract", cascade = CascadeType.ALL,fetch = FetchType.EAGER)
private List<ContractItem> contractItem;
//getters & setters...
}
.
#Entity(name = "ContractItem")
#Table( name = "contract_item")
public class ContractItem implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(unique = true, nullable = false)
private Long id;
#Column(name = "id_contract")
private Long idContract;
//getters & setters...
}
I'm extending JpaRepository im my repositories and using .save(contract) to persist but every time my application only persists the contract not de items, I've already tried CascadeType.ALL, MERGE and PERSIST in which either the result is the same, or I get an exception that my idContract must not be null.
Need some help here guys, thanks in advance !

How to maintain foreign key relationship in hibernate

I have two classes and I want to have a one to many relation between them, for e.g.:
Home(id<int>, rooms<string>)
Vehicle(id<int>, home_id<int>, name<string>)
I need to have a relation between Home and Vehicle class using Home.id and vehicle.home_id.
Please suggest any example which I can use here for CURD operation to implement REST service.
I need to have a relation between Home and Vehicle class using Home.id
and vehicle.home_id.
Your entities should look like this :
Vehicle Entity
#Entity
#Table(name = "vehicle", catalog = "bd_name", schema = "schema_name")
#XmlRootElement
public class Vehicle implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "id")
private Integer id;
#Column(name = "name")
private String name;
#JoinColumn(name = "home_id", referencedColumnName = "id")
#ManyToOne
private Home homeId;
//constructor getter & setters
}
Home Entity
#Entity
#Table(name = "home", catalog = "bd_name", schema = "schema_name")
#XmlRootElement
public class Home implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "id")
private Integer id;
#Column(name = "room")
private Character room;
#OneToMany(mappedBy = "homeId")
private List<Vehicle> vehicleList;
//constructor getter & setters
}

How can I convert this 3 JOIN query into a Spring Data JPA named query method?

I am not so into Spring Data JPA and I have the following problem trying to implement a named query (the query defined by the method name).
I have these 3 entity classes:
#Entity
#Table(name = "room_tipology")
public class RoomTipology implements Serializable{
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private Long id;
#Column(name = "tipology_name")
private String name;
#Column(name = "tipology_description")
private String description;
#Column(name = "time_stamp")
private Date timeStamp;
#OneToMany(mappedBy = "roomTipology")
private List<Room> rooms;
#OneToOne(mappedBy = "roomTipology")
private RoomRate roomRate;
// GETTER AND SETTER METHODS
}
That represents a tipology of room and that contains this field
#OneToMany(mappedBy = "roomTipology")
private List<Room> rooms;
So it contains the list of room associated to a specific room tipology, so I have this Room entity class:
#Entity
#Table(name = "room")
public class Room implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private Long id;
#ManyToOne
#JoinColumn(name = "id_accomodation_fk", nullable = false)
private Accomodation accomodation;
#ManyToOne
#JoinColumn(name = "id_room_tipology_fk", nullable = false)
private RoomTipology roomTipology;
#Column(name = "room_number")
private String number;
#Column(name = "room_name")
private String name;
#Column(name = "room_description")
#Type(type="text")
private String description;
#Column(name = "max_people")
private Integer maxPeople;
#Column(name = "is_enabled")
private Boolean isEnabled;
// GETTER AND SETTER METHODS
}
Representing a room of an accomodation, it contains this annoted field:
#ManyToOne
#JoinColumn(name = "id_accomodation_fk", nullable = false)
private Accomodation accomodation;
And finally the Accomodation entity class:
#Entity
#Table(name = "accomodation")
public class Accomodation implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private Long id;
#OneToMany(mappedBy = "accomodation")
private List<Room> rooms;
#Column(name = "accomodation_name")
private String name;
#Column(name = "description")
#Type(type="text")
private String description;
// GETTER AND SETTER METHODS
}
Ok, so now I have this Spring Data JPA repository class for RoomTipology:
#Repository
#Transactional(propagation = Propagation.MANDATORY)
public interface RoomTipologyDAO extends JpaRepository<RoomTipology, Long> {
}
Here I want to define a named query method that return to me the list of all the RoomTipology object related to a specific accomodation, I have done it using SQL and it works fine:
SELECT *
FROM room_tipology as rt
JOIN room r
ON rt.id = r.id_room_tipology_fk
JOIN accomodation a
ON r.id_accomodation_fk = a.id
WHERE a.id = 7
But now I want to translate it in a named query method (or at least using HQL)
How can I do it?
Please Try:
#Repository
#Transactional(propagation = Propagation.MANDATORY)
public interface RoomTipologyDAO extends JpaRepository<RoomTipology, Long> {
List<RoomTipology> findByRooms_Accomodation(Accomodation accomodation);
}
The query builder mechanism built into Spring Data repository infrastructure is useful for building constraining queries over entities of the repository. The mechanism strips the prefixes find…By, read…By, query…By, count…By, and get…By from the method and starts parsing the rest of it
At query creation time you already make sure that the parsed property is a property of the managed domain class. However, you can also define constraints by traversing nested properties.
Doc:Here

Categories