@Type with yes_no in Hibernate Annotation

By Arvind Rai, February 03, 2013
Hibernate Annotation @Type gives YES NO approach to insert data. In a scenario where we need to insert Y and N in database value. We can follow the Hibernate Annotation approach. What we need to do is Annotate our boolean property with @Type(type="yes_no"). When we insert true are false but in databse its value will be like Y/N.
Car.java
 package com.concretepage.persistence;

import java.io.Serializable;

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

import org.hibernate.annotations.Type;

@Entity
@Table(name="car")  
public class Car implements Serializable {
	private static final long serialVersionUID = 1L;
	@Id
	@GeneratedValue
	private int id;
		
	@Column(name="name")
	private String name;
	
	@Type(type="yes_no")
	private boolean newModel; 
	public Car(String name,boolean newModel){
		this.name=name;
		this.newModel=newModel;
	}
	
	public boolean isNewModel() {
		return newModel;
	}

	public void setNewModel(boolean newModel) {
		this.newModel = newModel;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}
}
HibernateUtil.java
package com.concretepage.util;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;

import com.concretepage.persistence.Car;

public class HibernateUtil {
	private static final SessionFactory concreteSessionFactory;
	    static {
	        try {
	            concreteSessionFactory = new AnnotationConfiguration()
	                    .configure().buildSessionFactory();
	        } catch (Throwable ex) {
	            throw new ExceptionInInitializerError(ex);
	        }
	    }
	    public static Session getSession()
	            throws HibernateException {
	        return concreteSessionFactory.openSession();
	    }
	    public static void main(String... args){
	    	Session session=getSession();
	    	session.beginTransaction();
	    	Car c1= new Car("Maruti",true);
	    	session.persist(c1);
	    	Car c2= new Car("Tata",false);
	    	session.persist(c2);
	    	session.getTransaction().commit();
	    	session.close();
	    }
	}
 
Value in database will look like
@Type with yes_no in Hibernate Annotation
POSTED BY
ARVIND RAI
ARVIND RAI







©2024 concretepage.com | Privacy Policy | Contact Us