Most Common Interview Questions

  1. What are your strengths?
  2. What are your weaknesses?
  3. Why are you interested in working for [insert company name here]?
  4. Where do you see yourself in five years? Ten years?
  5. Why do you want to leave your current company?
  6. Why was there a gap in your employment between [insert date] and [insert date]?
  7. What can you offer us that someone else can not?
  8. What are three things your former manager would like you to improve on?
  9. Are you willing to relocate?
  10. Are you willing to travel?
  11. Tell me about an accomplishment you are most proud of.
  12. Tell me about a time you made a mistake.
  13. What is your dream job?
  14. How did you hear about this position?
  15. What would you look to accomplish in the first 30 days/60 days/90 days on the job?
  16. Discuss your resume.
  17. Discuss your educational background.
  18. Describe yourself.
  19. Tell me how you handled a difficult situation.
  20. Why should we hire you?
  21. Why are you looking for a new job?
  22. Would you work holidays/weekends?
  23. How would you deal with an angry or irate customer?
  24. What are your salary requirements? (Hint: if you’re not sure what’s a fair salary range and compensation package, research the job title and/or company on Glassdoor.)
  25. Give a time when you went above and beyond the requirements for a project.
  26. Who are our competitors?
  27. What was your biggest failure?
  28. What motivates you?
  29. What’s your availability?
  30. Who’s your mentor?
  31. Tell me about a time when you disagreed with your boss.
  32. How do you handle pressure?
  33. What is the name of our CEO?
  34. What are your career goals?
  35. What gets you up in the morning?
  36. What would your direct reports say about you?
  37. What were your bosses’ strengths/weaknesses?
  38. If I called your boss right now and asked him what is an area that you could improve on, what would he say?
  39. Are you a leader or a follower?
  40. What was the last book you’ve read for fun?
  41. What are your co-worker pet peeves?
  42. What are your hobbies?
  43. What is your favorite website?
  44. What makes you uncomfortable?
  45. What are some of your leadership experiences?
  46. How would you fire someone?
  47. What do you like the most and least about working in this industry?
  48. Would you work 40+ hours a week?
  49. What questions haven’t I asked you?
  50. What questions do you have for me?

interview questions engineers struggle to answer

Q: How many trailing zeros are in the number 5! (5 factorial)?
Asked to: Systems engineer at Google
Suggested answers:
Option 1: 5!=120. So there is 1 trailing zero.
Option 2: This sounds like one geared not so much towards getting the right answer, but getting to it the right way. If you think a bit and say "one", the interviewer will know you did it the brute-force way, doing the math. You'd get at the answer faster, and probably impress them more, if you think instead how many times a ten will be produced in doing that math, rather than what the actual result of the math will be.
Q: You have two light bulbs at a 100-story building. You want to find the floor at which the bulbs will break when dropped. Find the floor using the least number of drops.
Asked to: Software engineer at Facebook
Suggested answers:
Option 1: Start moving up in increments of 10 floors and dropping the bulb until it breaks (ie: drop from floor 10, if it doesn't break, drop from floor 20, etc.) Once the bulb breaks, move down to the floor before it broke on and start moving up floors in increments of one until the second bulb breaks. This results in a worst case scenario of 19 drops.
Option 2: 19 drops is not the best worst-case scenario... imagine trying floor 16, if it breaks, you try 1 - 15 and thats 16 tries. If it doesn't break, then try floor 31 and if it breaks, then try 17 - 30 (so 16 tries, including the try on floor 16). And on and on (45, 58, 70, 81, 91, 100). If you reach 91, you'll have tried 7 floors so far and if it doesn't break, then there's 9 more tries to get to 100 (thus 16 in the worst case.)

Q: If you had 5,623 participants in a tournament, how many games would need to be played to determine the winner?
Asked to: Manager at Amazon
Suggested answers:
Option 1: The interviewer is not looking for the right answer because there can be many. What he/she is looking for is your logical approach in solving the answer. So you could start by probing more is first I would like to understand if 5,623 participants represent the number of team or individuals. Then ask the next logical question based on the answer."
Option 2: 5,622. Assuming it is a single elimination tournament. All teams lose one game except the champs. It's always # of teams - 1.
Q: There are 20 different socks of two types in a drawer in a completely dark room. What is the minimum number of socks you should grab to ensure you have a matching pair?
Asked to: Software development engineer in test at Web trends
Suggested answer: I'm not a mathematician, statistician, or highly analytical but if you pick up three socks they could still be all of same type -- even if the odds are 50%. Odds do not equal reality. So the only way to 'ensure you have a matching pair' is to pick up 11 of the 20. This is the only foolproof guaranteed way to get a pair (in the real world and not the world of odds.)
Q: If you have a square room with no roof, and you had four flagpoles you had to plant on the walls so that each flagpole touched two walls, how would you do it?
Asked to: Software engineer at Cisco
Suggested answer: The answer was that by planting them on the corners, each one is touching two walls because each corner is part of two walls. I wanted to pierce two walls with a pole horizontally too. They said it was an innovative solution.

Q: There are 9 balls all of which weigh the same except one, what is the minimum weighings necessary to find the ball weighs more (or less)?
Asked to: Software engineer at DE Shaw & Co
Suggested answer: You could do this with two weighings assuming its a two pan balance -- (1) place three balls on each side if they balance out then its the remaining three that has abnormal ball (2) out of that group, place one ball on each side -- if balances it out, the abnormal ball is the remaining one. If the weighing in step (1) does not balance out, grab the group of three balls that is light or heavy and repeat step (2) described above."

Q: You have 2 pieces of rope, each of which burns from one end to the other in 30 minutes (no matter which end is lit). If different pieces touch, the flame will transfer from one to the other. You cannot assume any rope properties that were not stated. Given only 1 match, can you time 45 minutes?
Asked to: ASIC verification engineer at Zoran
Suggested answers:
Option 1: Take one rope (Rope A), place it down as a circle. Light match and start burning rope A at the tips that are touching. When the rope completely burns out, 15 minutes will have passed (since both ends are burning and being consumed at once). Hold the second rope (Rope B) straight and place one end so that it will immediately catch fire when the two burning points from (Rope A) finally touch and are just about to burn out. Thus 15 minutes on Rope A + 30 minutes on Rope B gives you 45 mins.
Option 2: Make a T simple.

JAXB Annotations - java

AnnotationPackage Detail/Import statement
@XmlRootElementimport javax.xml.bind.annotation.XmlRootElement;
@XmlElementimport javax.xml.bind.annotation.XmlElement;
@XmlTypeimport javax.xml.bind.annotation.XmlType;
@XmlTransientimport javax.xml.bind.annotation.XmlTransient;
@XmlSeeAlsoimport javax.xml.bind.annotation.XmlSeeAlso;
Using JAXB and JPA Annotations in Conjunction
Using JAX-RS Annotations with JAXB and JPA Annotations

@XmlRootElement

Define the root element for the XML to be produced with @XmlRootElement JAXB annotation. The name of the root XML element is derived from the class name.
1
2
3
4
@XmlRootElement
public class Contact implements Serializable {
...
}
You can also specify the name of the root element of the XML using its name attribute, for example @XmlRootElement(name = "CompanyContact")

@XmlElement

Annotate all fields that needs to be included in XML/JSON output with @XMLElement.
1
2
3
4
@XmlElement
public String getName() {
  return name;
}
Either annotate all fields or all getter methods in your Entity bean. A mix of both is not supported. Add @XmlAccessorType(XmlAccessType.FIELD) at the class level if you want to annotate private fields instead of getter methods.

@XmlType

Specify the order in which XML elements or JSON output will be produced.
1
2
3
4
5
@XmlRootElement
@XmlType(propOrder = { "id", "firstName", "lastName", "email", "telephone" })
public class Contact implements Serializable {
...
}
The above @XmlType annotation will produce the following XML.
1
2
3
4
5
6
7
<contact>
    <id>38</id>
    <firstname>FirstName</firstname>
    <lastname>LastName</lastname>
    <email>dummyEmail@techferry.com</email>
    <telephone>1111111111</telephone>
</contact>
Similarly, it will produce the following JSON.
1
2
{"id":"38","firstName":"FirstName","lastName":"LastName",
"email":"dummyEmail@techferry.com","telephone":"1111111111"}

@XmlTransient

Annotate fields that we do not want to be included in XML or JSON output with @XMLTransient.
1
2
3
4
@XmlTransient
public Date getVersion() {
  return version;
}

@XmlSeeAlso

Use @XmlSeeAlso annotation when we want another Entity bean included in the XML output. In our example below, CompanyList bean refers to Company bean and the XML output should include XML generated from Company Entity too.
1
2
3
4
5
6
7
8
9
10
@XmlRootElement(name = "List")
@XmlSeeAlso(Company.class)
public class CompanyList {
 
  @XmlElement(name = "companyList")
  public List<Company> getList() {
    return list;
  }
...
}

To include more than 1 classes, we can use @XmlSeeAlso JAXB annotation as:
@XmlSeeAlso({ A.class, B.class }) 

Using JAXB and JPA Annotations in Conjunction

If you have reviewed both Hibernate - JPA Annotations and JAXB Annotations, the following snippet illustrates usage of both JAXB and JPA annotations in the same entity Contact.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
@Entity
@Table(name = "CONTACT")
@XmlRootElement
@XmlType(propOrder = { "id", "firstName", "lastName", "email", "telephone" })
public class Contact implements Serializable {
 
  @Id
  @Column(name = "ID")
  @GeneratedValue
  private Integer id;
 
  @Column(name = "firstName")
  private String firstName;
 
  @Column(name = "lastName")
  private String lastName;
 
  @Column(name = "EMAIL")
  private String email;
 
  @Column(name = "TELEPHONE")
  private String telephone;
 
  @Version
  @Column(name = "version")
  private Date version;
 
  @ManyToOne
  @JoinColumn(name = "companyId")
  private Company company;
 
  @OneToOne(mappedBy = "contact", cascade = CascadeType.ALL)
  private ContactDetail contactDetail;
 
  @XmlTransient
  public Company getCompany() {
    return company;
  }
 
  public void setCompany(Company company) {
    this.company = company;
  }
 
  @XmlTransient
  public ContactDetail getContactDetail() {
    return contactDetail;
  }
 
  public void setContactDetail(ContactDetail contactDetail) {
    this.contactDetail = contactDetail;
  }
 
  @XmlTransient
  public Date getVersion() {
    return version;
  }
 
  public void setVersion(Date version) {
    this.version = version;
  }
 
  @XmlElement
  public Integer getId() {
    return id;
  }
 
  public void setId(Integer id) {
    this.id = id;
  }
 
  @XmlElement
  public String getFirstName() {
    return firstName;
  }
 
  public void setFirstName(String firstName) {
    this.firstName = firstName;
  }
 
  @XmlElement
  public String getLastName() {
    return lastName;
  }
 
  public void setLastName(String lastName) {
    this.lastName = lastName;
  }
 
  @XmlElement
  public String getEmail() {
    return email;
  }
 
  public void setEmail(String email) {
    this.email = email;
  }
 
  @XmlElement
  public String getTelephone() {
    return telephone;
  }
 
  public void setTelephone(String telephone) {
    this.telephone = telephone;
  }
 
}

Using JAX-RS Annotations with JAXB and JPA Annotations

This section assumes that you have reviewed
RESTful JAX-RS Annotations, Hibernate - JPA Annotations and JAXB Annotations. Also see the section above on using JAXB and JPA Annotations in Conjunction.

Now that you have an entity bean containing both JAXB and JPA Annotations which is capable of doing data exchange with database and coverting it to required JSON/XML format, the next step is to send this data to rich clients using jQuery or Ext-js. In your REST based web-service methods, return the Contact entity bean as shown below. Jersey, JAXB will take care of data conversion and appropriate response generation.
1
2
3
4
5
6
7
@GET
@Produces("application/xml")
@Path("xml/{firstName}")
public Contact getXML(@PathParam("firstName") String firstName) {
  Contact contact = contactService.findByFirstName(firstName);
  return contact;
}
1
2
3
4
5
6
7
@GET
@Produces("application/json")
@Path("json/{firstName}")
public Contact getJSON(@PathParam("firstName") String firstName) {
  Contact contact = contactService.findByFirstName(firstName);
  return contact;
}

References:

  1. JAXB Annotations: http://docs.oracle.com/javaee/6/api/javax/xml/bind/annotation/package-summary.html

RESTful Web Service - JAX-RS Annotations




AnnotationPackage Detail/Import statement
@GETimport javax.ws.rs.GET;
@Producesimport javax.ws.rs.Produces;
@Pathimport javax.ws.rs.Path;
@PathParamimport javax.ws.rs.PathParam;
@QueryParamimport javax.ws.rs.QueryParam;
@POSTimport javax.ws.rs.POST;
@Consumesimport javax.ws.rs.Consumes;
@FormParamimport javax.ws.rs.FormParam;
@PUTimport javax.ws.rs.PUT;
@DELETEimport javax.ws.rs.DELETE;


REST follows one-to-one mapping between create, read, update, and delete (CRUD) operations and HTTP methods.

  • To create a resource on the server, use POST.
  • To retrieve a resource, use GET.
  • To change the state of a resource or to update it, use PUT.
  • To remove or delete a resource, use DELETE.

@GET

Annotate your Get request methods with @GET.
1
2
3
4
@GET
public String getHTML() {
  ...
}

@Produces

@Produces annotation specifies the type of output this method (or web service) will produce.
1
2
3
4
5
@GET
@Produces("application/xml")
public Contact getXML() {
  ...
}
1
2
3
4
5
@GET
@Produces("application/json")
public Contact getJSON() {
  ...
}

@Path

@Path annotation specify the URL path on which this method will be invoked.
1
2
3
4
5
6
@GET
@Produces("application/xml")
@Path("xml/{firstName}")
public Contact getXML() {
  ...
}

@PathParam

We can bind REST-style URL parameters to method arguments using @PathParam annotation as shown below.
1
2
3
4
5
6
7
@GET
@Produces("application/xml")
@Path("xml/{firstName}")
public Contact getXML(@PathParam("firstName") String firstName) {
  Contact contact = contactService.findByFirstName(firstName);
  return contact;
}
1
2
3
4
5
6
7
@GET
@Produces("application/json")
@Path("json/{firstName}")
public Contact getJSON(@PathParam("firstName") String firstName) {
  Contact contact = contactService.findByFirstName(firstName);
  return contact;
}

@QueryParam

Request parameters in query string can be accessed using @QueryParam annotation as shown below.
1
2
3
4
5
6
7
@GET
@Produces("application/json")
@Path("json/companyList")
public CompanyList getJSON(@QueryParam("start") int start, @QueryParam("limit") int limit) {
  CompanyList list = new CompanyList(companyService.listCompanies(start, limit));
  return list;
}
The example above returns a list of companies (with server side pagination) which can be displayed with rich clients implemented using Ext-js or jQuery. You can read more more about setting up ExtJS grid panel with remote sorting and pagination using Hibernate.

@POST

Annotate POST request methods with @POST.
1
2
3
4
5
6
@POST
@Consumes("application/json")
@Produces("application/json")
public RestResponse<Contact> create(Contact contact) {
...
}

@Consumes

The @Consumes annotation is used to specify the MIME media types a REST resource can consume.
1
2
3
4
5
6
7
@PUT
@Consumes("application/json")
@Produces("application/json")
@Path("{contactId}")
public RestResponse<Contact> update(Contact contact) {
...
}

@FormParam

The REST resources will usually consume XML/JSON for the complete Entity Bean. Sometimes, you may want to read parameters sent in POST requests directly and you can do that using @FormParam annotation. GET Request query parameters can be accessed using @QueryParam annotation.
1
2
3
4
5
@POST
public String save(@FormParam("firstName") String firstName,
    @FormParam("lastName") String lastName) {
      ...
  }

@PUT

Annotate PUT request methods with @PUT.
1
2
3
4
5
6
7
@PUT
@Consumes("application/json")
@Produces("application/json")
@Path("{contactId}")
public RestResponse<Contact> update(Contact contact) {
...
}

@DELETE

Annotate DELETE request methods with @DELETE.
1
2
3
4
5
6
@DELETE
@Produces("application/json")
@Path("{contactId}")
public RestResponse<Contact> delete(@PathParam("contactId") int contactId) {
...
}

References

  1. Jersey JAX-RS Annotations: https://wikis.oracle.com/display/Jersey/Overview+of+JAX-RS+1.0+Features



Hibernate JPA Annotations

AnnotationPackage Detail/Import statement
@Entityimport javax.persistence.Entity;
@Tableimport javax.persistence.Table;
@Columnimport javax.persistence.Column;
@Idimport javax.persistence.Id;
@GeneratedValueimport javax.persistence.GeneratedValue;
@Versionimport javax.persistence.Version;
@OrderByimport javax.persistence.OrderBy;
@Transientimport javax.persistence.Transient;
@Lobimport javax.persistence.Lob;
Hibernate Association Mapping Annotations
@OneToOneimport javax.persistence.OneToOne;
@ManyToOneimport javax.persistence.ManyToOne;
@OneToManyimport javax.persistence.OneToMany;
@ManyToManyimport javax.persistence.ManyToMany;
@PrimaryKeyJoinColumnimport javax.persistence.PrimaryKeyJoinColumn;
@JoinColumnimport javax.persistence.JoinColumn;
@JoinTableimport javax.persistence.JoinTable;
@MapsIdimport javax.persistence.MapsId;
Hibernate Inheritance Mapping Annotations
@Inheritanceimport javax.persistence.Inheritance;
@DiscriminatorColumnimport javax.persistence.DiscriminatorColumn;
@DiscriminatorValueimport javax.persistence.DiscriminatorValue;

@Entity

Annotate all your entity beans with @Entity.

1
2
3
4
@Entity
public class Company implements Serializable {
...
}

@Table

Specify the database table this Entity maps to using the name attribute of @Table annotation. In the example below, the data will be stored in 'company' table in the database.

1
2
3
4
5
@Entity
@Table(name = "company")
public class Company implements Serializable {
...
}

@Column

Specify the column mapping using @Column annotation.
1
2
3
4
5
6
7
8
9
@Entity
@Table(name = "company")
public class Company implements Serializable {
 
  @Column(name = "name")
  private String name;
   
...
}

@Id

Annotate the id column using @Id.
1
2
3
4
5
6
7
8
9
10
@Entity
@Table(name = "company")
public class Company implements Serializable {
 
  @Id
  @Column(name = "id")
  private int id;
   
...
}

@GeneratedValue

Let database generate (auto-increment) the id column.
1
2
3
4
5
6
7
8
9
10
11
@Entity
@Table(name = "company")
public class Company implements Serializable {
 
  @Id
  @Column(name = "id")
  @GeneratedValue
  private int id;
   
...
}

@Version

Control versioning or concurrency using @Version annotation.
1
2
3
4
5
6
7
8
9
10
@Entity
@Table(name = "company")
public class Company implements Serializable {
 
  @Version
  @Column(name = "version")
  private Date version;
   
...
}

@OrderBy

Sort your data using @OrderBy annotation. In example below, it will sort all contacts in a company by their firstname in ascending order.
1
2
@OrderBy("firstName asc")
private Set contacts;

@Transient

Annotate your transient properties with @Transient.

@Lob

Annotate large objects with @Lob.

Hibernate Association Mapping Annotations

Example App DB Schema

DB Schema
The database for this tutorial is designed to illustrate various association mapping concepts.
In RDBMS implementations, entities are joined using the following ways:
  • Shared Primary Key
  • Foreign Key
  • Association Table
In our example app,
  • Tables company and companyDetail have shared values for primary key. It is a one-to-one assoication.
  • Tables contact and contactDetail are linked through a foreign key. It is also a one to one association.
  • Tables contact and company are linked through a foriegn key in many-to-one association with contact being the owner.
  • Tables company and companyStatus are linked through a foreign key in many-to-one association with company being the owner.

@OneToOne

  • Use @PrimaryKeyJoinColumn for associated entities sharing the same primary key.
  • Use @JoinColumn & @OneToOne mappedBy attribute when foreign key is held by one of the entities.
  • Use @JoinTable and mappedBy entities linked through an association table.
  • Persist two entities with shared key using @MapsId
For entities Company and CompanyDetail sharing the same primary key, we can associate them using @OneToOne and @PrimaryKeyJoinColumn as shown in the example below.

Notice that the id property of CompanyDetail is NOT annotated with @GeneratedValue. It will be populated by id value of Company.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
@Entity
@Table(name = "company")
public class Company implements Serializable {
   
  @Id
  @Column(name = "id")
  @GeneratedValue
  private int id;
   
  @OneToOne(cascade = CascadeType.MERGE)
  @PrimaryKeyJoinColumn
  private CompanyDetail companyDetail;
   
  ...
}
 
@Entity
@Table(name = "companyDetail")
public class CompanyDetail implements Serializable {
 
  @Id
  @Column(name = "id")
  private int id;
   
  ...
}

For entities Contact and ContactDetail linked through a foriegn key, we can use @OneToOne and @JoinColumn annotations. In example below, the id genereated for Contact will be mapped to 'contact_id' column of ContactDetail table. Please note the usage of @MapsId for the same.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
@Entity
@Table(name = "contactDetail")
public class ContactDetail implements Serializable {
 
  @Id
  @Column(name = "id")
  @GeneratedValue
  private int id;
   
  @OneToOne
  @MapsId
  @JoinColumn(name = "contactId")
  private Contact contact;
   
  ...
}
 
@Entity
@Table(name = "contact")
public class Contact implements Serializable {
 
  @Id
  @Column(name = "ID")
  @GeneratedValue
  private Integer id;
 
  @OneToOne(mappedBy = "contact", cascade = CascadeType.ALL)
  private ContactDetail contactDetail;
 
  ....
}
Also note that the relationship between Company and CompanyDetail is uni-directional. On the other hand, the relationship between Contact and Contact Detail is bi-directional and that can be achieved using 'mappedBy' attribute.

The rationale to have one relationship as uni-directional and other as bi-directional in this tutorial is to illustrate both concepts and their usage. You can opt for uni-directional or bi-directional relationships to suit your needs.

@ManyToOne

  • Use @JoinColumn when foreign key is held by one of the entities.
  • Use @JoinTable for entities linked through an association table.
  • The two examples below illustrate many-to-one relationships. Contact to Company and Company to CompanyStatus. Many contacts can belong to a company. Similary many companies can share the same status (Lead, Prospect, Customer) - there will be many companies that are currently leads.
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    @Entity
    @Table(name = "contact")
    public class Contact implements Serializable {
     
      @ManyToOne
      @JoinColumn(name = "companyId")
      private Company company;
       
      ...
       
     }
     
    @Entity
    @Table(name = "company")
    public class Company implements Serializable {
     
      @ManyToOne
      @JoinColumn(name = "statusId")
      private CompanyStatus status;
       
      ...
       
     }

    @OneToMany

    • Use mappedBy attribute for bi-directional associations with ManyToOne being the owner.
    • OneToMany being the owner or unidirectional with foreign key - try to avoid such associations but can be achieved with @JoinColumn
    • @JoinTable for Unidirectional with association table
    Please see the many-to-one relationship between Contact and Company above. Company to Contact will be a one-to-many relationship. The owner of this relationship is Contact and hence we will use 'mappedBy' attribute in Company to make it bi-directional relationship.
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    @Entity
    @Table(name = "company")
    public class Company implements Serializable {
     
      @OneToMany(mappedBy = "company", fetch = FetchType.EAGER)
      @OrderBy("firstName asc")
      private Set contacts;
         
      ...
       
     }
    Again, for this tutorial, we have kept Company to CompanyStatus relationship as uni-directional.

    @ManyToMany

    • Use @JoinTable for entities linked through an association table.
    • Use mappedBy attribute for bi-directional association.

    @PrimaryKeyJoinColumn

    @PrimaryKeyJoinColumn annotation is used for associated entities sharing the same primary key. See OneToOne section for details.
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    @Entity
    @Table(name = "company")
    public class Company implements Serializable {
       
      @Id
      @Column(name = "id")
      @GeneratedValue
      private int id;
       
      @OneToOne(cascade = CascadeType.MERGE)
      @PrimaryKeyJoinColumn
      private CompanyDetail companyDetail;
       
      ...
    }

    @JoinColumn

    Use @JoinColumn annotation for one-to-one or many-to-one associations when foreign key is held by one of the entities. We can use @OneToOne or @ManyToOne mappedBy attribute for bi-directional relations. Also see OneToOne and ManyToOne sections for more details.
    1
    2
    3
    @ManyToOne
    @JoinColumn(name = "statusId")
    private CompanyStatus status;

    @JoinTable

    Use @JoinTable and mappedBy for entities linked through an association table.

    @MapsId

    Persist two entities with shared key (when one entity holds a foreign key to the other) using @MapsId annotation. See OneToOne section for details.
    1
    2
    3
    4
    @OneToOne
    @MapsId
    @JoinColumn(name = "contactId")
    private Contact contact;

    Hibernate Inheritance Mapping Annotations

    To understand Inheritance Mapping annotations, you must first understand Inheritance Mapping in Hiberate in detail. Once you understand Inheritance mapping concepts, please review below for annotations to be used.
  • table per class hierarchy - single table per Class Hierarchy Strategy: the <subclass> element in Hibernate
1
2
3
4
5
6
7
8
9
10
@Entity
@Inheritance(strategy=InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name="planetype", discriminatorType=DiscriminatorType.STRING )
 
@DiscriminatorValue("Plane")
public class Plane { ... }
 
@Entity
@DiscriminatorValue("A320")
public class A320 extends Plane { ... }
  • table per class/subclass - joined subclass Strategy: the <joined-subclass> element in Hibernate
  • 1
    2
    3
    4
    5
    6
    7
    @Entity
    @Inheritance(strategy=InheritanceType.JOINED)
    public class Boat implements Serializable { ... }
     
    @Entity
    @PrimaryKeyJoinColumn
    public class Ferry extends Boat { ... }
  • table per concrete class - table per Class Strategy: the <union-class> element in Hibernate
  • 1
    2
    3
    @Entity
    @Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
    public class Flight implements Serializable { ... }

  • Note: This strategy does not support the IDENTITY generator strategy: the id has to be shared across several tables. Consequently, when using this strategy, you should not use AUTO nor IDENTITY. 

    @Inheritance

    See Hibernate Inheritance Mapping Annotations section for details.
    1
    2
    @Entity
    @Inheritance(strategy=InheritanceType.SINGLE_TABLE)

    @DiscriminatorColumn

    See Hibernate Inheritance Mapping Annotations section for details.
    1
    2
    3
    @Entity
    @Inheritance(strategy=InheritanceType.SINGLE_TABLE)
    @DiscriminatorColumn(name="planetype", discriminatorType=DiscriminatorType.STRING )

    @DiscriminatorValue

    See Hibernate Inheritance Mapping Annotations section for details.
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    @Entity
    @Inheritance(strategy=InheritanceType.SINGLE_TABLE)
    @DiscriminatorColumn(name="planetype", discriminatorType=DiscriminatorType.STRING )
     
    @DiscriminatorValue("Plane")
    public class Plane { ... }
     
    @Entity
    @DiscriminatorValue("A320")
    public class A320 extends Plane { ... }

    References:

  • Hibernate Annotations: http://docs.jboss.org/hibernate/annotations/3.5/reference/en/html_single/
  • Inheritance Mapping Reference: http://docs.jboss.org/hibernate/core/3.5/reference/en/html/inheritance.html
  •  


     

     

 



 

Genuine websites to earn money.

If you are interested in PTC sites then this article is for you. I have personally tried many of the sites and found that the best thing ...