Welcome to Scribd, the world's digital library. Read, publish, and share books and documents. See more
Standard view
Full view
of .
Save to My Library
Look up keyword or section
Like this

Table Of Contents

0 of .
Results for:
No results containing your search query
P. 1
JPA Relationships

JPA Relationships

Ratings: (0)|Views: 2,626 |Likes:
Published by tlad

More info:

Published by: tlad on Apr 06, 2009
Copyright:Attribution Non-commercial


Read on Scribd mobile: iPhone, iPad and Android.
download as DOC, PDF, TXT or read online from Scribd
See more
See less





How to do Column Mapping with Hibernate and JPA Annotations
A simple tutorial on how to define your database columns based on your Java code, using Hibernate and JPA
Column Mapping
Okay, I'm pretty happy about all of the progress we've made so far. Using a fairly simple User class, we've explored all of the basic databaseoperations, looked at some of the fundamental JPA tags we can use to decorate our JavaBeans, and we've even explored some best practicesand design patterns through the HibernateUtil class. However, the fact remains that our User class is really starving from a lack of propertynutrition. It's time to add some more properties to the User class, and in the process, explore the following topics:
mapping columns with the @Column JPA Annotation
mapping to tables and schemas with the @Table JPA annotation
annotating non-persistent properties with the @Transient annotation
mapping advanced data types such as dates and large character objects
Adding the LoginName Property
 Now, one of the thing you may have noticed about the User example that we have been working with so far is the fact that the name of our table, along with the name of the table-columns, exactly matched the class and property names of the User POJO. There is definitelysomething to be said for keeping the first few examples simple; However, it's not too often that every database table and column is goingmap perfectly to the names used in your domain model.One of the fields I wanted to add to my User JavaBean was a loginName field. It just makes sense that a JavaBean named User, that containsa property named password, would also provide some way of maintaining a unique, identifying name for logging a user in. So, I want to adda field, of type String, to my User class, but the column in the User 
must be named login_name. I know it's not a huge difference, but itis enough to throw the Hibernate framework off a little bit. If the Hibernate framework sees a POJO with an identically named table, or afield in a JavaBean with an identically named database column, well, Hibernate does a great job of doing the Java to database mappings.However, when database and an POJO names do not coincide, you've got to add some new annotations to your JavaBeans.
The @Column Annotation
@Column(name="columnName";boolean unique() default false;boolean nullable() default true;boolean insertable() default true;boolean updatable() default true;String columnDefinition() default "";String table() default "";int length() default 255;int precision() default 0;int scale() default 0;)
Adding a Column Annotation
One of the great things about Hibernate is that it makes mapping data from your JavaBeans to the database fairly easy, even when changeshappen in either your object model, or your data model.Right now, we have the challenge of mapping a JavaBean field named loginName to a column named login_name in the database. Well,doing so really isn't all that complicated; it's just a matter of adding the appropriate variable declaration, setters and getters, and finally,adding a special @Column annotation that describes to Hibernate how to perform the field to database column mapping.
import javax.persistence.Column;@Entitypublic class User {private Long id;private String password;private String loginName; 
@Column (name="login_name")
public String getLoginName() {return loginName;}public void setLoginName(String loginName) {this.loginName = loginName;}
As you can see, mapping the loginName property to the login_name field in the database is as simple as adding the @Column annotation before the getLoginName() method, and providing the (name="login_name") attribute to the annotation.
Coding for the Updated loginName Field
To take advantage of the new field, all we need to do is add a line of code in the main method of the User class that initializes the loginName property, user.setLoginName("mj");. We can then commit the transaction to the database.
public static void main(String args[]){System.out.println("creating Hibernate config");AnnotationConfiguration config =new AnnotationConfiguration();config.addAnnotatedClass(User.class);SessionFactory factory;factory = config.configure().buildSessionFactory();Session session = factory.getCurrentSession();session.beginTransaction();System.out.println("creating user");User user = new User(); 
/*here is the new stuff!!!The instance is now named user,just to shake it up a bit. :) */
user.setPassword("abc123");session.save(user);System.out.println("user saved");session.getTransaction().commit();System.out.println("transaction successful!!!");}
Recreating the Database
Of course, if you try to persist the loginName field of the User to the database, you better make sure the user table in the database has acolumn named login_name, otherwise you'll be seeing an org.hibernate.exception.SQLGrammarException telling you about an

Activity (18)

You've already reviewed this. Edit your review.
1 hundred reads
1 thousand reads
viswama143 liked this
aberegov liked this
Artyom Novikov liked this
gotamo liked this
djmarcosroberto liked this
Rafael Ramírez liked this
vinay901 liked this
wdklotz liked this

You're Reading a Free Preview

/*********** DO NOT ALTER ANYTHING BELOW THIS LINE ! ************/ var s_code=s.t();if(s_code)document.write(s_code)//-->