How to use Hibernate Annotations to work with Database

How to use Hibernate Annotations to work with Database

Hibernate annotations is a solution to map Java classes and database’s tables without using XML file. So in the tutorial, JavaSampleApproach will guide you through the steps of configuring Hibernate Annotations to work with Database.

Related articles:
How to start development with Hibernate – XML Mapping File Hibernate

I. Technologies

– Java 1.8
– Maven 3.3.9
– Spring Tool Suite – Version 3.8.1.RELEASE
– Hibernate: 5.2.10.Final
– MySQL 5.7

II. Hibernate Annotations

We use annotations at standard package java.lang.annotation.* of EJB 3.
We have MySQL table:

CREATE TABLE customer(
   id INT NOT NULL AUTO_INCREMENT,
   firstname VARCHAR(20) NOT NULL,
   lastname VARCHAR(20) NOT NULL,
   age INT NOT NULL,
   PRIMARY KEY (id)
);

How to use annotations to map it with Java Entity class?

– Approach 1: use annotations on fields to access properties on an object through fields.

package com.javasampleapproach.hibernate.model;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "customer")
public class Customer {

	@Id @GeneratedValue(strategy = GenerationType.IDENTITY)
	@Column(name = "id")
	private int id;
	
	@Column(name = "firstname", nullable=false)
	private String firstName;
	
	@Column(name = "lastname", nullable=false)
	private String lastName;
	
	@Column(name = "age", nullable=false)
	private int age;
	
	public Customer(){};
	
	public Customer(String firstName, String lastName, int age){
		this.firstName = firstName;
		this.lastName = lastName;
		this.age = age;
	}
	
        // getters & setters
...

– Approach 2: use annotations on the getXXX() methods to enable access to properties through getter and setter methods.

package com.javasampleapproach.hibernate.model;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "customer")
public class Customer {

	private int id;

	private String firstName;

	private String lastName;

	private int age;

	public Customer() {
	};

	public Customer(String firstName, String lastName, int age) {
		this.firstName = firstName;
		this.lastName = lastName;
		this.age = age;
	}

	public void setId(int id) {
		this.id = id;
	}

	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	@Column(name = "id")
	public int getId() {
		return this.id;
	}

	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}

	@Column(name = "firstname", nullable = false)
	public String getFirstName() {
		return this.firstName;
	}

	public void setLastName(String lastName) {
		this.lastName = lastName;
	}

	@Column(name = "lastname", nullable = false)
	public String getLastName() {
		return this.lastName;
	}

	public void setAge(int age) {
		this.age = age;
	}

	@Column(name = "age", nullable = false)
	public int getAge() {
		return this.age;
	}

	public String toString() {
		String info = String.format("Customer info: id = %d, firstname = %s, lastname = %s, age = %d", id, firstName,
				lastName, age);
		return info;
	}

}

@javax.persistence.Entity: specifies the entity class.
– Having option attribute: name that is used for specifying a mapping table.

@javax.persistence.Column: specifies the mapped column for a persistent property or field. Below is common optional attributes of @Column:
name: is a column’s name , defaults to the property name.
unique: defines the column is a unique key, default is false.
nullable: specify the column is nullable, default value is true.
length: specify length of string-valued column.

@javax.persistence.Id: specifies the primary key of an entity.

@javax.persistence.GeneratedValue: generates the values of primary keys. It’s only supported for simple primary keys and Not supported for derived primary keys.

III. Practice

Step to do:
– Create Spring Maven project
– Create persistent class
– Setup Hibernate configuration
– Implement Hibernate Application
– Run & Check Results

1. Create Spring Maven project

Using Spring Tool Suite, create a Simple Spring Maven project.
Modified pom.xml file with Hibernate & MySql dependencies:


    4.0.0
    org.springframework.samples
    SpringHibernateStarter
    0.0.1
     
    
        
        
            org.hibernate
            hibernate-core
            5.2.10.Final
        
         
        
        
            mysql
            mysql-connector-java
            6.0.6
        
         
         
    

2. Create persistent class

Create a Customer.java:

package com.javasampleapproach.hibernate.model;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "customer")
public class Customer {

	@Id @GeneratedValue(strategy = GenerationType.IDENTITY)
	@Column(name = "id")
	private int id;
	
	@Column(name = "firstname", nullable=false)
	private String firstName;
	
	@Column(name = "lastname", nullable=false)
	private String lastName;
	
	@Column(name = "age", nullable=false)
	private int age;
	
	public Customer(){};
	
	public Customer(String firstName, String lastName, int age){
		this.firstName = firstName;
		this.lastName = lastName;
		this.age = age;
	}
	
	public void setId(int id){
		this.id = id;
	}
	
	public int getId(){
		return this.id;
	}
	
	public void setFirstName(String firstName){
		this.firstName = firstName;
	}
	
	public String getFirstName(){
		return this.firstName;
	}
	
	public void setLastName(String lastName){
		this.lastName = lastName;
	}
	
	public String getLastName(){
		return this.lastName;
	}
	
	public void setAge(int age){
		this.age = age;
	}
	
	public int getAge(){
		return this.age;
	}
	
	public String toString(){
		String info = String.format("Customer info: id = %d, firstname = %s, lastname = %s, age = %d", 
														id, firstName, lastName, age);
		return info;
	}

}
3. Setup Hibernate configuration

Under /src/main/resources, create Hibernate Configuration file – hibernate.cfg.xml:




    
    	jdbc:mysql://localhost:3306/testdb
        com.mysql.jdbc.Driver
        root
        12345
        org.hibernate.dialect.MySQL5Dialect
        create
        true
    

– We use property hibernate.hbm2ddl.auto with create value to init customer table automatically. Or we can manually create customer table by SQL script:

CREATE TABLE customer(
   id INT NOT NULL AUTO_INCREMENT,
   firstname VARCHAR(20) NOT NULL,
   lastname VARCHAR(20) NOT NULL,
   age INT NOT NULL,
   PRIMARY KEY (id)
);
4. Implement Hibernate Application

– Implement 6 functions:
setUpSessionFactory(): setup Hibernate Session Factory
saveCustomers(): save Customers to Database by Hibernate
showAllCustomers(): retrieve all customers from MySQL and show all on console.
updateCustomer(int customerId, int newAge): update Customer’s age.
deleteCustomer(int customerId): delete a customer
shutdown(): close Hiberbate Session Factory Object

package com.javasampleapproach.hibernate;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

import com.javasampleapproach.hibernate.model.Customer;

public class Application {
	private static SessionFactory factory = null;

	public static void main(String[] args) {

		System.out.println("============Set up Session Factory============");
		setUpSessionFactory();

		System.out.println("============Save Customers============");
		saveCustomers();

		System.out.println("============Show Customers============");
		showAllCustomers();

		System.out.println("============Update Customer - Peter with id = 1 & new age = 21============");
		updateCustomer(1, 21);

		System.out.println("============Delete Customer: Lauren with id = 3============");
		deleteCustomer(3);

		System.out.println("============Show Customers after Update & Delete============");
		// show all customer again - after update & delete
		showAllCustomers();

		shutdown();
	}

	public static void setUpSessionFactory() {
		// create sessionFactory
		try {
			factory = new Configuration().configure().addAnnotatedClass(Customer.class).buildSessionFactory();
		} catch (Throwable ex) {
			System.err.println("Failed to create sessionFactory object." + ex);
			throw new ExceptionInInitializerError(ex);
		}
	}

	public static void shutdown() {
		factory.close();
	}

	public static void saveCustomers() {
		
		Transaction tx = null;
		try(Session session = factory.openSession()) {
			tx = session.beginTransaction();

			// create customers
			Customer peter = new Customer("Peter", "Smith", 20);
			Customer mary = new Customer("Mary", "Taylor", 25);
			Customer lauren = new Customer("Lauren", "Taylor", 30);

			// save to database
			session.save(peter);
			session.save(mary);
			session.save(lauren);

			tx.commit();
		} catch (Exception e) {
			if (null != tx) {
				tx.rollback();
			}
		}
	}

	public static void showAllCustomers() {
		Transaction tx = null;
		try(Session session = factory.openSession()) {
			tx = session.beginTransaction();
			List customers = session.createQuery("FROM Customer", Customer.class).list();
			customers.forEach(System.out::println);
			tx.commit();
		} catch (Exception e) {
			if (null != tx) {
				tx.rollback();
			}
		}
	}

	public static void updateCustomer(int customerId, int newAge) {
		Transaction tx = null;
		try(Session session = factory.openSession()) {
			tx = session.beginTransaction();
			// update Peter: age = 21
			Customer cust = session.get(Customer.class, customerId);
			cust.setAge(newAge);
			session.update(cust);

			tx.commit();
		} catch (Exception e) {
			if (null != tx) {
				tx.rollback();
			}
		}
	}

	public static void deleteCustomer(int customerId) {
		Transaction tx = null;
		try(Session session = factory.openSession()) {
			tx = session.beginTransaction();

			// Employee employee =
			Customer cust = session.get(Customer.class, customerId);
			session.delete(cust);
			tx.commit();
		} catch (Exception e) {
			if (null != tx) {
				tx.commit();
			}
		}
	}
}
5. Run & Check Results

– Run the main class Application.java, Logs:

...
Hibernate: drop table if exists customer
May 17, 2017 11:14:14 AM org.hibernate.resource.transaction.backend.jdbc.internal.DdlTransactionIsolatorNonJtaImpl getIsolatedConnection
INFO: HHH10001501: Connection obtained from JdbcConnectionAccess [org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess@6622fc65] for (non-JTA) DDL execution was not in auto-commit mode; the Connection 'local transaction' will be committed and the Connection will be set into auto-commit mode.
Hibernate: create table customer (id integer not null auto_increment, age integer not null, firstname varchar(255) not null, lastname varchar(255) not null, primary key (id)) engine=MyISAM
May 17, 2017 11:14:14 AM org.hibernate.resource.transaction.backend.jdbc.internal.DdlTransactionIsolatorNonJtaImpl getIsolatedConnection
INFO: HHH10001501: Connection obtained from JdbcConnectionAccess [org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess@43b6123e] for (non-JTA) DDL execution was not in auto-commit mode; the Connection 'local transaction' will be committed and the Connection will be set into auto-commit mode.
May 17, 2017 11:14:14 AM org.hibernate.tool.schema.internal.SchemaCreatorImpl applyImportSources
INFO: HHH000476: Executing import script 'org.hibernate.tool.schema.internal.exec.ScriptSourceInputNonExistentImpl@3300f4fd'
============Save Customers============
Hibernate: insert into customer (age, firstname, lastname) values (?, ?, ?)
Hibernate: insert into customer (age, firstname, lastname) values (?, ?, ?)
Hibernate: insert into customer (age, firstname, lastname) values (?, ?, ?)
============Show Customers============
May 17, 2017 11:14:14 AM org.hibernate.hql.internal.QueryTranslatorFactoryInitiator initiateService
INFO: HHH000397: Using ASTQueryTranslatorFactory
Hibernate: select customer0_.id as id1_0_, customer0_.age as age2_0_, customer0_.firstname as firstnam3_0_, customer0_.lastname as lastname4_0_ from customer customer0_
Customer info: id = 1, firstname = Peter, lastname = Smith, age = 20
Customer info: id = 2, firstname = Mary, lastname = Taylor, age = 25
Customer info: id = 3, firstname = Lauren, lastname = Taylor, age = 30
============Update Customer - Peter with id = 1 & new age = 21============
Hibernate: select customer0_.id as id1_0_0_, customer0_.age as age2_0_0_, customer0_.firstname as firstnam3_0_0_, customer0_.lastname as lastname4_0_0_ from customer customer0_ where customer0_.id=?
Hibernate: update customer set age=?, firstname=?, lastname=? where id=?
============Delete Customer: Lauren with id = 3============
Hibernate: select customer0_.id as id1_0_0_, customer0_.age as age2_0_0_, customer0_.firstname as firstnam3_0_0_, customer0_.lastname as lastname4_0_0_ from customer customer0_ where customer0_.id=?
Hibernate: delete from customer where id=?
============Show Customers after Update & Delete============
Hibernate: select customer0_.id as id1_0_, customer0_.age as age2_0_, customer0_.firstname as firstnam3_0_, customer0_.lastname as lastname4_0_ from customer customer0_
Customer info: id = 1, firstname = Peter, lastname = Smith, age = 21
Customer info: id = 2, firstname = Mary, lastname = Taylor, age = 25
...

– Customer’s records:

hibernate annotation - customer records

IV. Sourcecode

SpringHibernateAnnotations

77 thoughts on “How to use Hibernate Annotations to work with Database”

  1. Hi, i think that i saw you visited my site so i came to
    “return the favor”.I am trying to find things to improve
    my website!I suppose its ok to use some of your ideas!!

  2. Hello would you mind stating which blog platform
    you’re using? I’m planning to start my own blog in the near future but I’m having a tough time
    making a decision between BlogEngine/Wordpress/B2evolution and Drupal.
    The reason I ask is because your design seems different then most blogs and I’m looking for something
    completely unique. P.S Apologies for
    getting off-topic but I had to ask!

  3. Aw, this was an extremely nice post. Finding the time and
    actual effort to create a good article… but
    what can I say… I hesitate a whole lot and don’t seem
    to get anything done.

  4. You really make it seem really easy along with your presentation however I
    in finding this matter to be actually something that I think I’d never understand.
    It sort of feels too complex and very wide for me.
    I’m taking a look forward on your next put up, I’ll attempt to
    get the grasp of it!

  5. I’m not sure where you’re getting your info, but good topic.
    I needs to spend some time learning much more or understanding more.

    Thanks for magnificent information I was looking for this information for my mission.

  6. Do you mind if I quote a couple of your articles as long as I provide credit and sources back to your website?
    My blog is in the very same niche as yours and my users would truly benefit from a lot of the information you present here.
    Please let me know if this alright with you. Thanks a lot!

  7. I think this is one of the most vital information for me.
    And i am glad reading your article. But want to remark on few general things,
    The website style is perfect, the articles is really great : D.

    Good job, cheers

  8. Great goods from you, man. I’ve understand your stuff previous to and you’re just too excellent.

    I actually like what you’ve acquired here, really like what you’re stating and the way in which you
    say it. You make it entertaining and you still take
    care of to keep it wise. I can’t wait to read far more from you.
    This is really a great website.

  9. I used to be suggested this website via my cousin. I’m
    no longer sure whether this publish is written by him as nobody else recognize such specific approximately my problem.
    You’re incredible! Thank you!

  10. My spouse and I stumbled over here by a different page and
    thought I might as well check things out.
    I like what I see so i am just following you. Look forward to exploring your web page repeatedly.

  11. I will immediately grab your rss as I can not in finding your email subscription hyperlink or newsletter service.
    Do you’ve any? Please allow me recognize in order
    that I may subscribe. Thanks.

  12. Excellent goods from you, man. I have understand yojr stuff
    previous to and you are just extremely great. I ctually like what you
    have acquired here, certainly like what you are
    saying and the wayy in which you say it. You make it entertaining and you still care for to
    keep it smart.I can’t wait to resad far more from you. This is actually
    a wonderful web site.

  13. Hi there, i read your blog from time to time and i own a similar one and i was just curious if you get a lot of spam feedback?
    If so how do you prevent it, any plugin or anything you
    can advise? I get so much lately it’s driving me crazy so any help is very much appreciated.

  14. I know this if off topic but I’m looking into starting my own weblog and was wondering what all is
    needed to get setup? I’m assuming having a blog like yours
    would cost a pretty penny? I’m not very internet smart so I’m not 100% sure.
    Any suggestions or advice would be greatly appreciated.
    Thank you

  15. An impressive share! I’ve just forwarded this onto a co-worker
    who had been doing a little research on this. And he actually bought me breakfast due to the fact that I stumbled upon it for him…
    lol. So let me reword this…. Thank YOU for the meal!!
    But yeah, thanks for spending time to talk about this topic here on your web page.

  16. Hi there, i read your blog occasionally and i own a similar one and i was
    just curious if you get a lot of spam comments? If so how do you prevent
    it, any plugin or anything you can advise? I get so much lately it’s driving me insane so any assistance is very much appreciated.

  17. Do you mind if I quote a few of your posts as long as I provide credit and sources back to
    your weblog? My blog is in the exact same area of interest as yours and my users would
    definitely benefit from a lot of the information you present here.
    Please let me know if this alright with you. Many thanks!

  18. Excellent weblog right here! Also your site so much up very fast!
    What host are you using? Can I get your affiliate hyperlink
    to your host? I want my site loaded up as quickly as yours lol

  19. Today, I went to the beachfront with my children. I found a sea shell and gave it to my 4 year old daughter and said “You can hear the ocean if you put this to your ear.” She placed
    the shell to her ear and screamed. There was a
    hermit crab inside and it pinched her ear. She never wants to go back!

    LoL I know this is totally off topic but I had to tell someone!

  20. Ahaa, its good dialogue concerning this piece of writing at this place at this web site, I have read all that,
    so now me also commenting at this place.

  21. When I originally commented I seem to have clicked
    on the -Notify me when new comments are added- checkbox and now every time a comment is added I get 4 emails with the exact same comment.
    Perhaps there is an easy method you can remove
    me from that service? Thanks!

  22. Great post. I was checking constantly this blog and I am inspired!

    Very helpful info specially the final part 🙂 I maintain such info
    much. I used to be looking for this certain information for a very long time.
    Thank you and good luck.

  23. My spouse and I stumbled over here from a different website and thought I might as well check things out.

    I like what I see so now i’m following you. Look forward to exploring your web page again.

  24. 619521 268478You produced some decent points there. I looked online for the concern and identified most people might go as nicely as making use of your internet web site. 283308

  25. Thank you for the auspicious writeup. It in fact was once a enjoyment
    account it. Glance complex to far added agreeable from you!
    By the way, how can we keep up a correspondence?

  26. I’m impressed, I have to admit. Seldom do I come across a blog that’s both educative
    and interesting, and let me tell you, you have hit the nail on the
    head. The problem is something which not enough men and women are
    speaking intelligently about. I’m very happy I came across
    this during my search for something concerning this.

  27. Hi, i read your blog occasionally and i own a similar one and i was just curious if you get a lot of spam remarks?
    If so how do you reduce it, any plugin or anything you can suggest?
    I get so much lately it’s driving me insane so any support is very much appreciated.

  28. Appreciating the commitment you put into your website and in depth information you present.
    It’s awesome to come across a blog every once in a while that isn’t the same out of date rehashed information. Excellent read!
    I’ve bookmarked your site and I’m including your
    RSS feeds to my Google account.

  29. Hello my loved one! I want to say that this article is awesome, nice written and come with almost
    all important infos. I’d like to look extra posts like this .

  30. I’ve been exploring for a little bit for any high-quality
    articles or weblog posts on this sort of area . Exploring in Yahoo I ultimately stumbled upon this web site.

    Reading this information So i’m satisfied to express that I’ve a very just right uncanny feeling I discovered exactly what I
    needed. I so much surely will make sure to do not
    forget this site and provides it a glance on a relentless basis.

  31. It’s the best time to make some plans for the future and it’s
    time to be happy. I’ve read this post and if I
    could I want to suggest you few interesting things or advice.
    Maybe you can write next articles referring to this article.

    I wish to read even more things about it!

  32. Unquestionably believe that which you said. Your favorite reason appeared to be
    on the internet the simplest thing to be aware of. I say to you,
    I certainly get irked while people consider worries that they just don’t know
    about. You managed to hit the nail upon the top as well as defined
    out the whole thing without having side-effects , people can take a signal.
    Will probably be back to get more. Thanks

  33. Aw, this was an incredibly good post. Taking the time
    and actual effort to make a top notch article… but what can I say… I put things off a whole lot and don’t seem to get anything done.

  34. Thank you for any other excellent article. The place else could anybody get that type
    of information in such a perfect approach of writing? I’ve a presentation next week,
    and I’m on the search for such info.

  35. You really make it appear so easy with your presentation however I to find this topic to be really something which I believe I
    would by no means understand. It kind of feels too complicated and extremely vast for me.
    I am looking ahead in your subsequent post, I’ll try to get the hold of
    it!

  36. Greetings! This is my first comment here so I just wanted
    to give a quick shout out and say I really enjoy reading through
    your blog posts. Can you recommend any other blogs/websites/forums that cover the same topics?
    Thank you!

  37. Hi, Neat post. There’s an issue along with your
    website in internet explorer, would check this?
    IE nonetheless is the marketplace chief and a large part of other
    people will leave out your wonderful writing because of this problem.

  38. Nice post. I learn something new and challenging on websites
    I stumbleupon everyday. It’s always interesting to read content from other authors and use a little something from other web sites.

  39. Generally I do not read article on blogs, however I wish to say that
    this write-up very forced me to take a look
    at and do it! Your writing style has been amazed me.
    Thanks, very nice article.

  40. Have you ever considered about adding a little bit more than just your articles?
    I mean, what you say is fundamental and everything. But just imagine
    if you added some great visuals or videos to give your posts more, “pop”!
    Your content is excellent but with images and videos, this website could definitely be one of
    the greatest in its niche. Superb blog!

  41. whoah this weblog is magnificent i like studying your
    articles. Stay up the good work! You realize,
    a lot of individuals are looking around for this info, you could help
    them greatly.

  42. Excellent blog here! Also your website loads up very fast!
    What host are you using? Can I get your affiliate link to your host?

    I wish my site loaded up as fast as yours lol

  43. Hi there, I believe your site could possibly be having internet browser compatibility
    issues. When I look at your blog in Safari, it looks fine however,
    if opening in Internet Explorer, it’s got some overlapping issues.
    I just wanted to give you a quick heads up! Aside from that,
    great blog!

  44. You could definitely see your expertise within the article you write.
    The arena hopes for more passionate writers like you who aren’t afraid to mention how they believe.
    Always follow your heart.

  45. Nice post. I learn something totally new and challenging on sites I stumbleupon every day.

    It’s always useful to read through content from other writers and practice a little something from other websites.

Leave a Reply

Your email address will not be published. Required fields are marked *