How can I load only specific child object to a mapping place holder - jpa

I have following object mapping in our project. One contact can have multiple quotes from typeA and typeB.
#Entity
#Table(name = "t_ind_contact")
public class Contact implements Serializable {
#Id
#Column(name = "id", unique = true)
private Long id;
#OneToMany
private List<Quote> quotes;
}
Abstract Quote class.
#Entity
#Inheritance
#DiscriminatorColumn(name = "app_code")
#Table(name = "t_ind_quote")
public abstract class Quote implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Column(name = "id")
private long id;
#OneToMany
#JoinColumn(name = "contact_id")
private Contact contact;
#Column(name = "app_code", insertable = false, updatable = false)
private int appCode;
}
TypeA Quote class
#Entity
#DiscriminatorValue("1")
public class TypeAQuote implements Serializable {
private static final long serialVersionUID = 1L;
}
TypeB Quote class
#Entity
#DiscriminatorValue("2")
public class TypeBQuote implements Serializable {
private static final long serialVersionUID = 1L;
}
This mapping is working fine for all operations. But for some operations we need the contact object with typeA quotes only. As of now, we will filter typeA quotes after system loads data from the database.
Is there a way that we can populate a contact object only with typeA quotes? I mean even the generated queries will load only typeA quotes.

Related

Query for joins in Spring JPA

I have the below entities
#Entity
#Getter
#Setter
public class Aggregate {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#OneToMany(mappedBy = "aggregate")
private Set<Single> singleSet;
}
#Entity
#Getter
#Setter
public class Single {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private String id;
private Integer number;
#ManyToOne
#JoinColumn(name = "agg_id")
private Aggregate aggregate;
}
I also have the below repository
public interface AggregateRepo extends CrudRepository<Aggregate, Long> {
}
I want to return all associated Single records where number in object Single is equal to some random number
I am assuming that the query will be something like this
public interface AggregateRepo extends CrudRepository<Aggregate, Long> {
public List<Single> findBySingleSet_Number(Integer number);
}
However when I try to use Intellij to complete my named query it always populates like this
public interface AggregateRepo extends CrudRepository<Aggregate, Long> {
public List<Single> findBySingleSet_Empty_Number(Integer number);
}
I am wondering what the Empty stands for ?
Also should I create another Single repository since the query is related to returning Single records.

JPA two Entities one Relationship: How do I obtain a Set of an entity that is linked through a relationship?

I have three tables each mapping to one of these entities. The 'assigned' table acts as the relationship between 'users' and 'roles' with a foreign key to each table. How would I map this on my entities so that I can get a Set of EntityRoles from the UserEntity? I can't quite figure out how to make this work. Is this even possible?
#Entity
#Table(name = "users")
public class UserEntity {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name="user_id")
private long id;
#Column(name="user_username")
private String username;
#Column(name="user_password")
private String password;
#Column(name="user_email")
private String email;
//I want to be able to get a set of RoleEntities
#OneToMany(fetch = FetchType.LAZY, mappedBy = "id")
private Set<RoleEntity> roles;
}
#Entity
#Table(name = "assigned")
public class AssignedEntity implements Serializable {
#Id
//#Column(name = "assigned_role")
#ManyToOne(targetEntity = RoleEntity.class, fetch = FetchType.LAZY)
#JoinColumn(name = "fk_role")
private long roleId;
#Id
//#Column(name = "assigned_user")
#ManyToOne(targetEntity = UserEntity.class, fetch = FetchType.LAZY)
#JoinColumn(name = "fk_user")
private long userId;
}
#Entity
#Table(name = "roles")
public class RoleEntity implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name="role_id")
#OneToOne(fetch = FetchType.LAZY, mappedBy="roleId")
private long id;
#Column(name="role_name")
private String name;
}
You are using an incorrect/inconvenient mapping. Always keep things as simply as possible.
#Entity
#Table(name = "users")
public class User {
#Id
#GeneratedValue
private Long id;
#ManyToMany(fetch = FetchType.LAZY)
private List<Role> roles;
}
#Entity
#Table(name = "roles")
public class Role {
#Id
private Long id;
#Column
private String name;
}
A persistent provider will create a (valid) join table for you. You can specify the name of the join table using #JoinTable annotation. Also you will need to think about auto generation values of id for the Role entity: the roles table is something like a reference data table. So, probably, you will need to hardcode the id values.
To get user roles (in the persistent context):
user.getRoles()

#OneToMany JPA Relationships toward the same Class

I'm building a simple Spring Application, I need help finding the right design for some JPA Entities, here is the case that I have :
One FirstResource Has many Actions
One SecondResource Has many Actions
One ThirdResource Has many Actions
My goal : I want to be able to add actions to a specific
resource, or list all the actions done on a resource for example.
The 4 Entities are (FirstResource, SecondResource, ThirdResource, Action), Should they be like this ? :
#Entity
public class Action implements Serializable {
#Id #GeneratedValue(strategy = GenerationType.IDENTITY)
private Long idAction;
private String nameAction; // + gettes & setters...
}
#Entity
public class FirstResource implements Serializable {
#Id #GeneratedValue(strategy = GenerationType.IDENTITY)
private Long idFirstResource;
private int unitNumber; // + gettes & setters...
}
#Entity
public class SecondResource implements Serializable {
#Id #GeneratedValue(strategy = GenerationType.IDENTITY)
private Long idSecondResource;
private String nameSecondResource; // + gettes & setters...
}
#Entity
public class ThirdResource implements Serializable {
#Id #GeneratedValue(strategy = GenerationType.IDENTITY)
private Long idThirdResource;
private boolean Confirmed; // + gettes & setters...
}
So should the class Action have references annotated with #ManyToOne to each of the Resources ? If yes, Is there a better way to do this ?
You could use inheritance.
Define an abstract class AbstractResource as an Entity :
#Entity
public abstract class AbstractResource implements Serializable {
#Id #GeneratedValue
private long id;
#OneToMany
private List<Action> actions;
...
}
Then make sure your resources class extend AbstractResource :
#Entity
public class FirstResource extends AbstractResource
And then you can reference your resources inside your Action entity :
#Entity
public class Action implements Serializable {
#Id #GeneratedValue(strategy = GenerationType.IDENTITY)
private Long idAction;
#ManyToOne
private AbstractResource resource;
...
}
As you cannot use MappedSuperClass with ManyToOne relations, you cannot use #MappedSuperClass in your case.

JPA OneToOne not working

I followed by tutorial : http://www.codejava.net/frameworks/hibernate/hibernate-one-to-one-mapping-with-foreign-key-annotations-example
I have following code:
#Entity
#Table(name = DomainConstant.TABLE_USER)
public class User{
#Id
#Column(name = DomainConstant.DOMAIN_USER_ID)
#GeneratedValue
private Long userId;
private UserActivationCode userActivationCode;
///////////////////// CONSTRUCTOR....
/// STANDARD GET AND SET....
#OneToOne(cascade = CascadeType.ALL)
#JoinColumn(name = DomainConstant.DOMAIN_ACTIVATION_LINK_ID)
public UserActivationCode getUserActivationCode() {
return userActivationCode;
}
}
#Entity
#Table(name = DomainConstant.TABLE_USER_ACTIVATON_LINK)
public class UserActivationCode {
#Id
#Column(name = DomainConstant.DOMAIN_ACTIVATION_LINK_ID)
#GeneratedValue
private Long userActivationCodeId;
#Column(name = DomainConstant.DOMAIN_ACTIVATION_DATE)
#Temporal(javax.persistence.TemporalType.DATE)
private Date date;
#Column(name = DomainConstant.DOMAIN_ACTIVATION_CODE)
private String code;
///////////////////// CONSTRUCTOR....
/// STANDARD GET AND SET....
}
When I save the User object it does not make record in UserActivationCode, why?
Like this:
User newUser = new User();
newUser.setUserActivationCode(new UserActivationCode("this is example"));
userDao.save(newUser);
I have record only in user table.
Can you tell me why?
Your problem is that you are mixing access types. In the User entity you have specified #Id on a field (private Long userId) whereas you have defined the join mapping on a property (the getter to UserActivationCode). If you specify the join mapping on the field, it should work as is.
#Entity
#Table(name = DomainConstant.TABLE_USER)
public class User{
#Id
#Column(name = DomainConstant.DOMAIN_USER_ID)
#GeneratedValue
private Long userId;
#OneToOne(cascade = CascadeType.ALL)
#JoinColumn(name = DomainConstant.DOMAIN_ACTIVATION_LINK_ID)
private UserActivationCode userActivationCode;
///////////////////// CONSTRUCTOR....
/// STANDARD GET AND SET....
public UserActivationCode getUserActivationCode() {
return userActivationCode;
}
}
For more information on access and access types, see Access, Java EE 7

JPA reusing code by extending without inheritance

I have two or more tables resembles each other.
PARENT
ID | PK
NAME | VARCHAR
CHILD
ID |PK
NAME | VARCHAR
AGE | INT
It's not #Inheritance situation because they are independent entities and related to each other by #OneToMany or #ManyToOne.
I create entity class for each other.
#Entity
public class Parent {
#Id
private Long id;
private String name;
#ManyToOne(mappedBy = "parent")
private Collection<Child> children;
}
#Entity
public class Child {
#Id
private Long id;
private String name;
private int age;
#OneToMany
private Parent parent;
}
Is there any nice way to share common fields mappings?
// #MappedSuperclass // is this what it is exactly for?
public abstract class Base {
// #Id protected Long id; // ##?
#Column(name = "name", nullable = false)
private String name;
}
#Entity
public class Parent extends Base {
#Id
#TableGenerator(...)
#GeneratedValue(...)
protected Long id;
#ManyToOne(mappedBy = "parent")
private Collection<Child> children;
}
#Entity
public class Child extends Base {
#Id
#TableGenerator(...)
#GeneratedValue(...)
protected Long id;
private int age;
#OneToMany
private Parent parent;
}
Is this OK?
Is it even possible declaring #Id protected Long id; on the Base leaving #TableGenerator and #GeneratedVAlue on extended classes?
Is there any nice way to share common fields mappings?
MappedSuperclass is exactly right tool for that.
Is it even possible declaring #Id protected Long id; on the Base
leaving #TableGenerator and #GeneratedVAlue on extended classes?
No, it is not possible.