简体   繁体   中英

Using @Transient Annotation for persistance storage

I have an object which contains multiple attributes. one of the attribute of my object is another object containing ArrayList. Hierarchy is as follow.

Object - Organization
(
String orgId
String orgName
String parentOrgName

Organization.Workers workers  //Object of Worker list...

)

I want to store Organization object in imdb (in memory database). I am using Hibernate session for database connection.

I have already set Worker object as Transient like this.

@Transient
protected Organization.Workers workers;

When I retrieve Organization, every time I get this worker object as null. Kindly guide me about use of @transient annotation and also tell about how to store nested objects in imdb using hibernate sessions in java spring.

@Transient annotation is used to tell JPA not to store field in the database. Also, whenever you are dealing with composition, figure out the relationship they have in between them.

In above example, the relationship seems to be one-to-many as one organization can have many workers but one worker can work in only one organization at a time.

You will have to tell JPA about this relationship using @OneToMany annotation.

Checkout this official link of Hibernate on how to use it.

The @Transient annotation is used when you need that specific field for certain work but are not willing that field to store in the database.

Here as your question is stated, there are organization and workers, so the relationship is @OneToMany relationship.

In Organization Class:

@OneToMany(cascade=CascadeType.ALL, fetch=FetchType.LAZY, mappedBy="organization")
private List<Workers> workers = new ArrayList<>();

In Workers Class:

@ManyToOne
@JoinColumn(name="id", unique=true)
private Organization organization;

Here, 1 organization can have many workers and one worker can only work on 1 organization. there you have it. :D

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM