JPA query method to find by elements in a List? - jpa

I have the following two entities (Contact and Participation, linked by a ManyToMany relation) :
#Entity
public class Contact {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private Long id;
#Column(nullable=false)
private String firstName;
#Column(nullable=false)
private String lastName;
#ManyToOne
private Company company;
#ManyToMany(fetch=FetchType.EAGER)
private List<Participation> participations;
}
#Entity
public class Participation {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private Long id;
#ManyToOne
private Company company;
private Status status;
}
I can't figure out how to get Contacts who have a specific Participation in their list. Should I look via Contacts with a specific JPA repository method (findBy...) ? Or would i have to look via the table which was created with both Contact and Participation IDs (ManyToMany) ?
Thanks!

Related

Send via http element's parent's id with #OneToMany relationship

I want to be able to send via http the entire ProjectUrl list exactly as it appears in my postgres DB, with columns "id", "url" and "project_id" (just the id, not the whole project); and at the same time, to be able to send the projects with their urls. So using #JsonIgnore on the "project" property or on the "List" can't do the trick for me... Of course if i don't use #JsonIgnore, recursion takes over. Thanks!
#Entity
public class ProjectUrl {
#Id
#GeneratedValue
private UUID id;
#NonNull
private String url;
#JsonIgnore
#ManyToOne(fetch = FetchType.LAZY)
private Projects project;
//getters and setters...
}
#Entity
public class Projects {
#Id
#GeneratedValue
private UUID id;
private String title;
private String description;
#OneToMany(mappedBy = "project", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
private List<ProjectUrl> urls = new ArrayList<ProjectUrl>();
//getters and setters...
}

JEE, JPA facade edit many to many relation

I'm facing an issue i can't figure out.
I got 2 entities : User and Course with a Many to Many relationship
User.java
public class User implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String username;
private String password;
#ManyToMany(cascade = CascadeType.MERGE)
#JoinTable(
name="USR_COURSES",
joinColumns=#JoinColumn(name="USR_ID", referencedColumnName="ID"),
inverseJoinColumns=#JoinColumn(name="COURSE_ID",referencedColumnName="ID"))
private List<Course> courses;
...
Course.java
#Entity
#Table(uniqueConstraints=#UniqueConstraint(columnNames="CODE"))
public class Course implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String code;
private String name;
private String content;
#ManyToMany(mappedBy="courses",cascade = CascadeType.MERGE)
private List<User> users;
...
If i create a user and set him some courses, the join table will be updated with the new relations between the User and the Courses.
However if i want to edit a user by adding him courses, the join table is not update :
List<Course> test = myUser.getCourse();
test.add(facade.find(1l));
myUser.setCourse(test);
userFacade.edit(myUser);
I'm using NetBean and the AbstractFacade generated.
Thanks for helping !
In order for the cascade to work in that case you would need to set dependencies in the both sides of the ManyToMany relationship.
That means that you would need to do the following:
List<Course> test = myUser.getCourse();
Course course = facade.find(1l);
course.getUsers().add(myUser);
test.add(course);
myUser.setCourse(test);
userFacade.edit(myUser);
When you query for the Course you do not get the user list because you only have Cascade.MERGE set up on that relationship. This means that you need to set it manually as above.

Load data from two OneToMany relationships

I want to display data from a database with JPA on the frontend, i.e. display the Person's details. Details can be 0..n Adresses and 0..m Phones. The entities are shown below:
#Entity
public class Person implements Serializable {
#Id #GeneratedValue
private int id;
private String name;
#OneToMany(mappedBy="person")
private List<Address> addresses = new ArrayList<Address>();
#OneToMany(mappedBy="person")
private List<Phone> phones = new ArrayList<Phone>();
// plus getter and setter
}
#Entity
public class Address implements Serializable {
#Id #GeneratedValue
private int id;
#ManyToOne
private Person person;
private String onestring; // plus getter and setter
}
#Entity
public class Phone implements Serializable {
#Id #GeneratedValue
private int id;
#ManyToOne
private Person person;
private String anotherstring; // plus getter and setter
}
As lazy loading is activated, ...
#PersistenceContext
private EntityManager em;
public Person getPerson(int id) {
return em.find(Person .class, id);
}
... would only provide proxies on adresses and phones.
Questions:
What is good way displaying the all data on the frontend, i.e. the person and all its addesses and phones? (Except for setting FetchType to EAGER).
Is there a way to fetch both addresses and phones into the same instance of Person or do I have to fetch the Person twice (one time with addresses, one time with phones) to omit a cartesian product?

how to develop JPA bi-directional entities in spring toot

I am new to spring boot and jpa/hibernate, please bear my inaccurate usage of the terminologies.
I have two entities: book and address. A book is published in a certain city which is stored in "address", a "address" can publish multiple books.
The DB schema for book is: id, name, author, price, addressid
schema for address: addressid, addressCountry, addressCity
The entity for book:
#Entity
#Table(name = "test_book")
public class Book implements Serializable {
private static final long serialVersionUID = 8025948150436422040L;
#Id
long id;
#Column(name = "name")
String name;
#Column(name = "author")
String author;
#Column(name = "price")
long price;
#ManyToOne
#JoinColumn(name = "addressid")
private Address address;
...//getter and setter
The entity for address
#Entity
#Table(name = "test_address")
public class Address implements Serializable{
private static final long serialVersionUID = -3541059157210384355L;
#Id
#Column(name= "addressid")
private long addressId;
#Column(name="addresscountry")
private String addressCountry;
#Column(name="addresscity")
private String addressCity;
#OneToMany(mappedBy = "address")
private Collection<Book> books;
...//getter setter
But when I call the Restful service, I get infinite loop...
[{"id":11,"name":"Java Book","author":"Jame Gosling","price":100,"address":{"addressId":1,"addressCountry":"China","addressCity":"Shanghai","books":[{"id":11,"name":"Java Book","author":"Jame Gosling","price":100,"address":...
I did some search. And my request is:
when I search a book, I can get the information: id, name, author, price, address..
And also I can query a address to get all the books the city published.
When I add Json Annotation #JsonManagedReference in address and #JsonBackReference in book entity, I can query book but cannot get address information.
Could you please help how to solve the problems? Thank you very much.
You can ignore the #JsonIgnore on getter for books. This will exclude the Collection<Book> books property from serialization the Address.
Link : JacksonAnnotations - Faster XML Wiki
Example:
#JsonIgnore
public Collection<Book> getBooks() {
...
}
#JsonIgnore
The Jackson annotation #JsonIgnore is used to tell Jackson to ignore a
certain property (field) of a Java object. The property is ignored
both when reading JSON into Java objects, and when writing Java
objects into JSON.
In your case this is happening as there is bidirectional relationship and so it will go into loop. To stop this you need to provide JsonIgnore
And so your code will be like :
-> The entity for address
#Entity
#Table(name = "test_address")
public class Address implements Serializable{
private static final long serialVersionUID = -3541059157210384355L;
#Id
#Column(name= "addressid")
private long addressId;
#Column(name="addresscountry")
private String addressCountry;
#Column(name="addresscity")
private String addressCity;
#OneToMany(mappedBy = "address")
#JsonIgnore
private Collection<Book> books;

How to map existing JPA entities to PicketLink

I am trying to migrate a Seam 2 app to CDI and use PicketLink for security. After all the reading and researching, it seems like all the examples are having one to one mapping between PicketLink model and the backend entity. e.g. Account to AccountEntity, Partition to PartitionEntity. Since I already have entities in place representing identity model, I am stuck on trying to map them to PicketLink. Here is what I have:
#MappedSuperClass
public class ModelEntityBase implement Serializable {
#Id #Generated
Long id;
Date creationDate;
}
#Entity
public Account extends ModelEntityBase {
String username;
String passwordHash;
#OneToOne(mappedBy = "account")
Person person;
}
#Entity
public Person extends ModelEntityBase {
String name;
String email;
#OneToOne
#JoinColumn(name = "account_id")
Account account;
}
Two entities (plus a super class) representing a single identity model in PicketLink, e.g. stereo type User.
Based on this why IdentityType id is String not Long, I tried to add a new Entity in:
#Entity
#IdentityManaged(BaseIdentityType.class);
public class IdentityTypeEntity implement Serializble {
#Id #Identifier
private String id;
#OneToOne(optional = false, mappedBy = "identityType")
#OwnerReference
private Account account;
#IdentityClass
private String typeName;
#ManyToOne #OwnerReference
private PartitionEntity partition;
}
I've tried a few different ways with the annotation and model classes. But when using IdentityManager.add(myUserModel), I just can't get it to populate all the entities. Is this even possible?
Got help from Pedro (PicketLink Dev). Post the answer here to help others.
This is the model class I ended up using.
#IdentityStereotype(USER)
public class User extends AbstractAttributedType implements Account {
#AttributeProperty
private Account accountEntity;
#AttributeProperty
#StereotypeProperty(IDENTITY_USER_NAME)
#Unique
private String username;
#AttributeProperty
private boolean enabled;
#AttributeProperty
private Date createdDate;
#AttributeProperty
private Date expiryDate;
#AttributeProperty
private Partition partition;
// getter and setter omitted
}
And created a new entity to map to this model:
public class IdentityTypeEntity implements Serializable {
#Id
#Identifier
private String id;
#OneToOne(optional = false, mappedBy = "identityType",
cascade = CascadeType.ALL, fetch = FetchType.EAGER)
#AttributeValue
// #NotNull
private HAccount accountEntity;
#IdentityClass
private String typeName;
#ManyToOne
#OwnerReference
private PartitionEntity partition;
#AttributeValue
private String username;
#AttributeValue
// #Transient
private boolean enabled;
#AttributeValue
private Date createdDate;
#AttributeValue
private Date expiryDate;
}
PL can map property with #AttributeProperty to entity property with #AttributeValue. But it can only map to one entity. Therefore there is no way to map, say User and its properties over to Account and Person. But you can have the entity (in my case accountEntity) in the model. I also have to duplicate a few fields in the new IdentityTypeEntity and my existing Account entity (username, eanbled, createdDate) because PL requires these. Use a #PrePersist and similar to sync them.