A brief analysis of the custom types in the Java Hibernate framework _java

Source: Internet
Author: User

Recently saw the custom type of hibernate, this has not been contacted before, recorded here, when it is the consolidation of their own knowledge, but also have not contacted friends to study some. The
 1) custom type, as the name suggests, is of course the type that is implemented by itself because the internal type does not meet the requirements. This situation is not much, but we still need to learn, more than the pressure body. Also learn how others in the framework of the time is how to consider, how to think of extensibility.
  Custom type has two methods to implement, one is to implement usertype, another implementation of Compositeusertype, there may be some methods, but I do not have the time to speak.
  I'm only using usertype for the time being, so let's take a look at the definition of the Usertype interface:

Public interface Usertype {/** * return the SQL type codes for the columns mapped by this type. 
   The * codes are defined on <TT>JAVA.SQL.TYPES</TT>. 
 
  * * Public int[] SqlTypes (); 
   /** * The class returned by <tt>nullsafeget () </tt>. 
 
  * * Public Class returnedclass (); 
   /** * Compare Two instances of the class mapped by this type for persistence "equality". 
   * Equality of the persistent state. 
 
  * * Public Boolean equals (object X, Object y) throws hibernateexception; /** * Get a hashcode to the instance, consistent with persistence "equality" */public int hashcode (Object x) 
 
  Throws Hibernateexception; /** * Retrieve A instance of the mapped class from a JDBC resultset. 
   Implementors * should handle possibility of null values. 
 
  * * Public Object Nullsafeget (ResultSet rs, string[] names, Object owner) throws Hibernateexception, SQLException; /** * Write An instance of the mappedclass to a prepared statement. Implementors * should handle possibility of null values. 
   A multi-column type should is written * to parameters starting from <tt>index</tt>. 
 
  * * public void Nullsafeset (PreparedStatement st, Object value, int index) throws Hibernateexception, SQLException; /** * Return a deep copy of the "persistent state", stopping at entities and at * collections. It isn't necessary to copy immutable objects, or null * values, in which case it's safe to simply return the Argumen 
 
  T. */public object Deepcopy (object value) throws Hibernateexception; 
   /** * Are objects of this type mutable? 
 
  * * @return Boolean */public boolean ismutable (); /** * Transform the object into its cacheable representation. At the very least this * method should perform a deep copy if the type is mutable. That May is enough * for some implementations, however; For example, associations must is cached as
   * Identifier values. (Optional operation) * * @param value the object to be cached * @return a cachable representation of the OBJEC 
 
  T * @throws hibernateexception */public Serializable disassemble (Object value) throws hibernateexception; /** * Reconstruct an object from the cacheable representation. At the very least this * method should perform a deep copy if the type is mutable. 
 
  (Optional operation) */public object Assemble (Serializable cached, Object owner) throws Hibernateexception; /** * During Merge, replace the existing (target) value in the entity we are merging to * with a new (original) VA Lue from the detached entity we are merging. For immutable * objects, or null values, it's safe to simply return the ' the ' the ' I parameter. for * mutable objects, it's safe to return a copy of the The ' the ' the ' the ' 
   For objects * and component values, it might make sense to recursively replace component values. * * PubLic Object Replace (object original, object target, object owner) throws Hibernateexception; 
 }

In fact, we can understand the general situation of English, no more explanations, here we are the most important is to implement the Nullsafeset () method, this method is mainly used to save this type of value to the database, this time we learn how to use, and then we slowly study how the interior is to achieve.
2 The example I write when I study is to refer to the example of Xia Xin, so it certainly is the same as most of the internet, we just analyze it roughly:
The following is the user class

Package org.hibernate.tutorial.domain; 
Import java.io.Serializable; 
Import java.util.List; 
public class User implements serializable{public 
  Long ID; 
  private String name; 
  Private List emails; 
    Omit Get/set Method 
} 

Down is the custom emaillist class:

Package org.hibernate.tutorial.domain; 
Import java.io.Serializable; 
Import java.sql.PreparedStatement; 
Import Java.sql.ResultSet; 
Import java.sql.SQLException; 
Import Java.sql.Types; 
Import java.util.ArrayList; 
Import java.util.List; 
Import Org.hibernate.Hibernate; 
Import org.hibernate.HibernateException; 
 
Import Org.hibernate.usertype.UserType; 
  public class Emaillist implements usertype {private static final char SPLITTER = '; '; 
   
  private static final int[] TYPES = new int[] {Types.varchar}; 
    Private String Assemble (List emaillist) {StringBuilder strbuf = new StringBuilder (); 
    for (int i = 0; i < emaillist.size ()-1; i++) {Strbuf.append (Emaillist.get (i)). Append (SPLITTER); 
    } strbuf.append (Emaillist.get (Emaillist.size ()-1)); 
  return strbuf.tostring (); Private List Parse (String value) {string[] STRs = Org.hibernate.util.StringHelper.split (value,string.valueo 
    F (SPLITTER)); List emaillist = new ArrayList ();
    for (int i = 0;i < Strs.length; i++) {Emaillist.add (strs[i)); 
  return emaillist; 
    The public object Deepcopy (object value) throws Hibernateexception {List sourceList = (list) value; 
    List targetlist = new ArrayList (); 
    Targetlist.add (sourceList); 
  return targetlist; 
  Serializable disassemble (Object value) throws hibernateexception {return null; 
     
    public Boolean equals (object X, Object y) throws Hibernateexception {if (x = = y) return true; 
     
    System.out.println ("X:" +x+ "Y:" +y); 
      if (x!= null && y!= null) {List xlist = (list) x; 
       
      List ylist = (list) y; 
       
      if (Xlist.size ()!= ylist.size ()) return false; 
        for (int i = 0; i < xlist.size (); i++) {String str1 = (string) xlist.get (i); 
         
        String str2 = (string) ylist.get (i); 
      if (!str1.equals (STR2)) return false; 
    return true; 
     
}    return false; 
  public Boolean ismutable () {return false; Public Object Nullsafeget (ResultSet rs, string[] names, Object owner) throws Hibernateexception, Sqlexceptio 
    n {String value = (string) Hibernate.STRING.nullSafeGet (RS, names[0]); 
    if (value!= null) {return parse (value);//pass list through; split} else{null; } public void Nullsafeset (PreparedStatement st, Object value, int index) throws Hibernateexception, Sqlex 
     
    ception {System.out.println ("Set method executed!"); 
     
    System.out.println ("Value:" + value); if (value!= null) {string str = assemble ((List) value); concatenation of strings; Hibernate.STRING.nullSafeSet (St, S 
    TR, index); 
    else {Hibernate.STRING.nullSafeSet (St, value, index); 
  } public Class Returnedclass () {return list.class; 
  Int[] SqlTypes () {return TYPES; 
 }//Omit other methods that do not need to be modified}

A method implemented in a class is a method that needs to be modified, and other methods that do not need to be modified temporarily are not written, but need to be implemented.
3 Next is the User Class mapping file:

<class name= "user" table= "user" > 
    <id name= "id" column= "user_id" type= "Java.lang.Long" > 
      < Generator class= "native"/> 
    </id> 
    <property name= "name" type= "string" column= "user_name"/> 
    <property name= "emails" type= "org.hibernate.tutorial.domain.EmailList" column= "emails"/> 
  </ Class> 

I believe we all know how to modify, here also do not explain, the main is to modify the type of emails, modified for we just defined the Emaillist class.
4 Finally, let's write a test class:

Import Java.util.HashMap; 
Import java.util.List; 
Import Java.util.Map; 
Import java.util.ArrayList; 
 
Import Junit.framework.TestCase; 
Import Org.hibernate.EntityMode; 
Import org.hibernate.Session; 
Import Org.hibernate.SessionFactory; 
Import org.hibernate.Transaction; 
Import org.hibernate.cfg.Configuration; 
 
Import Org.hibernate.tutorial.domain.User; 
   
  public class Hibernatetest extends testcase{private session = NULL; 
    protected void SetUp () throws Exception {Configuration cfg = new Configuration (). Configure (); 
     
    Sessionfactory sessionfactory = Cfg.buildsessionfactory (); 
 
  Session = Sessionfactory.opensession (); 
    public void Testinsert () {Transaction Tran = null; 
       
      try{tran = Session.begintransaction (); 
       
      User user = new user (); 
       
      User.setname ("Shun"); 
       
      List List = new ArrayList (); 
      List.add ("12312@sfsdf.com"); 
 
    List.add ("123@123.com");  User.setemails (list); 
       
      Session.save (user); 
    Tran.commit (); 
      catch (Exception ex) {ex.printstacktrace (); 
      if (tran!= null) {tran.rollback (); 
  }} protected void Teardown () throws Exception {session.close (); 
 } 
}

Here may be a problem, when we only save an email, it will appear abnormal, in the database is the email field is empty, and when we like the above code, there are two, there will be no problem, the database results as shown in the picture:

And when we save only one, the exception is as follows:

Java.lang.ClassCastException:java.util.ArrayList cannot be cast to java.lang.String 

It occurs in a string str1 = (string) xlist.get (i) in the Emaillist's Equals method, which is checked to be the list when inserting data into the Emaillist Nullsafeset method, That
Value:[[12312@sfsdf.com, 123@123.com]] such a form, so that when compared to the problem, it will always have a value, and in the comparison of the time is different,

if (Xlist.size ()!= ylist.size ()) return false; 

So there is a problem when casting.
And after checking, the Equals method:

X:[[12312@sfsdf.com, 123@123.com]]y:[12312@sfsdf.com, 123@123.com] 

  The result is very strange. The internet does not talk about why this is happening. Here is a point: I use the hibernate version is Hibernate 3.3.2.GA. I don't know if it's a version or some other problem, we'll look into it tomorrow. If any of the brothers know why, I hope you will not hesitate to tell me.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.