<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Elegando &#187; Hibernate</title>
	<atom:link href="http://elegando.jcg3.org/cat/hibernate/feed/" rel="self" type="application/rss+xml" />
	<link>http://elegando.jcg3.org</link>
	<description>elegant » being unusually effective and simple...</description>
	<lastBuildDate>Mon, 01 Mar 2010 20:17:04 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.1</generator>
		<item>
		<title>Hibernate @GeneratedValue</title>
		<link>http://elegando.jcg3.org/2009/08/hibernate-generatedvalue/</link>
		<comments>http://elegando.jcg3.org/2009/08/hibernate-generatedvalue/#comments</comments>
		<pubDate>Thu, 06 Aug 2009 00:59:26 +0000</pubDate>
		<dc:creator>Jason G.</dc:creator>
				<category><![CDATA[Hibernate]]></category>

		<guid isPermaLink="false">http://elegando.jcg3.org/2009/08/hibernate-generatedvalue/</guid>
		<description><![CDATA[I spent a bit of time figuring out what all the annotations for a Hibernate/JPA @Id field should be, and wanted to document it. First up, with any entity, you need to add an @Id annotation to a field, I typically use a Long field. package test.model; import javax.persistence.*; import java.io.Serializable; @Entity @Table(name="test_table") public class [...]]]></description>
			<content:encoded><![CDATA[<p>I spent a bit of time figuring out what all the annotations for a Hibernate/JPA @Id field should be, and wanted to document it.</p>
<p>First up, with any entity, you need to add an @Id annotation to a field, I typically use a Long field.<span id="more-116"></span></p>
<pre class="java" name="code">package test.model;

import javax.persistence.*;
import java.io.Serializable;

@Entity
@Table(name="test_table")
public class TestTable implements Serializable {
    private static final long serialVersionUID = 1L;

    @Id
    @Column(name="test_table_id")
    private Long id;

    // getters &amp; setters
}</pre>
<p>All is good and well, until we want to persist new TestTable objects.  Now we need a @GeneratedValue annotation&#8230;  you can use a variety of strategies: GenerationType.AUTO, IDENTITY, SEQUENCE, or TABLE.  Auto will have Hibernate guess at which version is best for your database type (e.g., a sequence for Oracle, an identity for MS SQL).</p>
<p>One requirement I typically have is that the application code and resultant data structure be database agnostic, and more specifically, have the same index strategy despite different databases.  So, we can define a strategy that will be implemented the same regardless of database type.</p>
<p>For a TABLE generation strategy, you can simply specify the strategy.  This will result in a table &#8220;hibernate_sequences&#8221; and a caching size of 10 (I think).</p>
<pre class="java" name="code">@Id
@Column(name="test_table_id")
@GeneratedValue(strategy=GenerationType.TABLE)
private Long id;</pre>
<p>This is fine, but Hibernate is actually caching the index number for you, and only writing out the index to table every 10 or so inserts.  We will want to change that (despite the performance hit) if we have anything that may not be using Hibernate to access these indexes.</p>
<p>The following will do the same as above (hibernate_sequences table), but flush the index out on every increment of the index.  The &#8220;generatorName&#8221; below is just an arbitrary name that pairs the two annotations.</p>
<pre class="java" name="code">@Id
@Column(name="test_table_id")
@GeneratedValue(strategy=GenerationType.TABLE, generator="generatorName")
@TableGenerator(name="generatorName", allocationSize=1)
private Long id;</pre>
<p>Want more control?  It&#8217;s available&#8230;  Here we&#8217;ll specify the table to put the sequences into, in case there was an existing table strategy used in some other project that you&#8217;d like to work with.</p>
<pre class="java" name="code">@Id
@Column(name="test_table_id")
@GeneratedValue(strategy=GenerationType.TABLE, generator="generatorName")
@TableGenerator(name="generatorName", table="TableID",
				pkColumnName="tablename", // TableID.TableName (value = table_name, test_table, etc.)
				valueColumnName="id", // TableID.ID (value = 1,2,3,etc.)
				allocationSize=1 // flush every 1 insert
)
private Long id;</pre>
<p>We can also use a custom coded IdentifierGenerator when using Hibernate.  The class MyIdGenerator extends IdentifierGenerator in the example below.  I also chose to implement Configurable so I could pass the table name into the generator.</p>
<pre class="java" name="code">// new imports
import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.Parameter;
// annotations for ID field
@Id
@Column(name="test_table_id")
@GeneratedValue(generator="UniqueIdGenerator")
@GenericGenerator(name="UniqueIdGenerator", strategy="test.util.MyIdGenerator",
	parameters = { @Parameter(name="tableName", value="test_table") } )
private Long id;</pre>
<p>And here is the ID generator&#8230;</p>
<pre class="java" name="code">package test.util;

import java.io.Serializable;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

import org.hibernate.HibernateException;
import org.hibernate.MappingException;
import org.hibernate.dialect.Dialect;
import org.hibernate.engine.SessionImplementor;
import org.hibernate.id.Configurable;
import org.hibernate.id.IdentifierGenerator;
import org.hibernate.type.Type;

public class MyIdGenerator implements IdentifierGenerator, Configurable {
	private String tableName;

    public void configure( Type arg0, Properties props, Dialect arg2 )
            throws MappingException {
        setTableName( props.getProperty( "tableName" ) );
    }

    public Serializable generate( SessionImplementor session, Object arg1 )
            throws HibernateException {
        // we want to open a new connection / transaction
        Connection conn = session.getBatcher().openConnection();

        Serializable id = null;
        try {
            id = new IdGenerator().generate( conn, tableName );
        } catch( SQLException e ) {
            throw new HibernateException( e );
        } finally {
            session.getBatcher().closeConnection( conn );
        }
        return id;
    }

    // getter &#038; setter for the configurable parameters
    public String getTableName() {
        return tableName;
    }
    public void setTableName( String tableName ) {
    	this.tableName = tableName;
    }
}</pre>
]]></content:encoded>
			<wfw:commentRss>http://elegando.jcg3.org/2009/08/hibernate-generatedvalue/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Hibernate Validation</title>
		<link>http://elegando.jcg3.org/2009/04/hibernate-validation/</link>
		<comments>http://elegando.jcg3.org/2009/04/hibernate-validation/#comments</comments>
		<pubDate>Wed, 15 Apr 2009 17:43:19 +0000</pubDate>
		<dc:creator>Jason G.</dc:creator>
				<category><![CDATA[Hibernate]]></category>

		<guid isPermaLink="false">http://www.elegando.com/2009/04/hibernate-validation/</guid>
		<description><![CDATA[Here’s a list of annotations that you can use to validate java beans: @Length(min=, max=) Checks whether the string length matches the range @Max(value=) Checks that the value is less than or equal to the max @Min(value=) Checks that the value is greater than or equal to the min @NotNull Checks that the value is [...]]]></description>
			<content:encoded><![CDATA[<p>Here’s a list of annotations that you can use to validate java beans:</p>
<ul>
<li>@Length(min=, max=) Checks whether the string length matches the range</li>
<li>@Max(value=) Checks that the value is less than or equal to the max</li>
<li>@Min(value=) Checks that the value is greater than or equal to the min</li>
<li>@NotNull Checks that the value is not null</li>
<li>@Past For a date object, checks that the date is in the past</li>
<li>@Future For a date object, checks that the date is in the future</li>
<li>@Pattern(regex=”regexp”, flag=) For a string, checks that the string matches this pattern</li>
<li>@Range(min=, max=) Checks whether the value is between the min and the max</li>
<li>@Size(min=, max=) For collections, checks that the size is between the two</li>
<li>@AssertFalse Asserts that the evaluation of the method is false</li>
<li>@AssertTrue Asserts that the evaluation of the method is true</li>
<li>@Valid For a collection or a map, checks that all the objects they contain are valid</li>
<li>@Email Checks whether the string conforms to the email address specification</li>
</ul>
<p>From <a href="http://depressedprogrammer.wordpress.com/2008/06/24/jsf-seam-validation-custom-messages-annotations-internationalization/">Depressed Programmer</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://elegando.jcg3.org/2009/04/hibernate-validation/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>
