Hibernate _ note 32 (considering custom ing types and creating usertypes)

Source: Internet
Author: User

For custom ing types, take the Address class ing in the previous section as an example:

   
    
    
  
 

This value type ing is very simple. All attributes of the new Java type are mapped to separate columns of the built-in SQL data type. However, you can also use a custom ing type to map it as a simple property:

   
    
    
  
 

Of course, in this example, the advantage of replacing component ing with custom ing types is questionable. As long as no special conversion is required to load and save this object, the CustomAddressType that must be compiled now is an additional task. However, you may have seen that the custom ing type provides an additional buffer-something that may come in handy when additional conversions are required during long-term operation.
Extended point Hibernate provides several interfaces that an application may use to define custom ing types. These interfaces reduce the work involved in creating new ing types and protect custom types from Hibernate core changes. This helps you easily upgrade Hibernate and retain existing custom ing types.
The extension points are as follows:
Org. hibernate. usertype. UserType -- Basic extension point for multiple scenarios. It provides basic methods for loading and storing custom value type instances.
Org. hibernate. usertype. CompositeUserType -- contains an interface that contains more methods than the basic UserType. Generally, the internal information about the value type class is exposed to Hibernate, such as individual attributes. Then, you can reference these attributes in the Hibernate query.
Org. hibernate. usertype. UserCollectionType -- rarely used to implement custom set interfaces. The custom ing type for this interface is not declared in property ing, but only useful for custom set ing. This type is required if you want to persist a non-JDK set and persist the extra principles.
Org. hibernate. usertype. enhanceUserType -- extends UserType and provides interfaces for additional methods. These methods are used to mail value types to XML notation (or to mail value types from XML Notation ), you can also enable a custom ing type to be used in ing between identifiers and identifiers.
Org. hibernate. usertype. UserVersionType -- extends UserType and provides additional method interfaces. This leads to custom ing types used for ing object versions.
Org. hibernate. usertype. ParameterizedType -- a useful interface that can be combined with all other interfaces to provide configuration settings -- that is, parameters defined in metadata.
In the case of custom ing type, the Bid class defines an amount attribute, and the Item class defines an initialPrice attribute, both of which are currency values. So far, we only use a simple BigDecimal to represent the value and map it to a single NUMBERIC column through big_decimal.
Suppose you want to support multiple currencies in the auction application, and you must reconstruct the existing domain model for this (customer-driven) change.
Create a new MonetaryAmount class that encapsulates the currency and amount.
import org.apache.commons.lang3.builder.EqualsBuilder;import org.apache.commons.lang3.builder.HashCodeBuilder;public class MonetaryAmount implements Serializable {private static final long serialVersionUID = -3446177576184667883L;private final BigDecimal amount;private final Currency currency;public MonetaryAmount(BigDecimal amount, Currency currency) {super();this.currency = currency;this.amount = amount;}public BigDecimal getAmount() {return amount;}public Currency getCurrency() {return currency;}public boolean equals(Object obj) {if (null == obj) {return false;}if (obj == this) {return true;}if (obj.getClass() != this.getClass()) {return false;}MonetaryAmount ma = (MonetaryAmount) obj;return new EqualsBuilder().append(this.getAmount(), ma.getAmount()).isEquals();}public int hashCode() {final int PRIME = 31;return new HashCodeBuilder(this.getAmount().intValue(), PRIME).toHashCode();}}
Note: You must implement equals () and hashCode () to complete the class.
Create UserType imagine that you are using a legacy database that represents the amount of all currencies in USD. This application is no longer limited to a single currency (this is the focus of refactoring), but it takes some time for the database team to change. When the persistent MonetaryAmount object is used, the amount must be converted to USD. When a database is loaded, it is converted back to the currency type you select based on your preference.
Package cn. jbit. hibernate. entity; import java. io. serializable; import java. math. bigDecimal; import java. SQL. preparedStatement; import java. SQL. resultSet; import java. SQL. SQLException; import java. util. currency; import org. hibernate. hibernateException; import org. hibernate. type. bigDecimalType; import org. hibernate. usertype. userType; public class MonetaryAmountType implements UserType {// tell Hibernate what SQL column type to use to generate DDL mode public int [] sqlTypes () {return new int [] {BigDecimalType. INSTANCE. sqlType () };}// ing Java value type @ SuppressWarnings ("unchecked") public Class returnedClass () {return MonetaryAmount. class;} // whether this type is variable public boolean isMutable () {return false;} // create a value snapshot public Object deepCopy (Object value) throws HibernateException {return value ;} // cache public Serializable disassemble (Object value) throws HibernateException {return (Serializable) value ;} // convert the cached data to an instance of MonetaryAmount public Object assemble (Serializable cached, Object owner) throws HibernateException {return cached ;} // merge public Object replace (Object original, Object target, Object owner) throws HibernateException {return original;} public boolean equals (Object x, Object y) throws HibernateException {if (x = y) return true; if (null = x | null = y) return false; return x. equals (y);} public int hashCode (Object x) throws HibernateException {return x. hashCode ();} // obtain the attribute value from the JDBC ResultSet public Object nullSafeGet (ResultSet resultSet, String [] names, Object owner) throws HibernateException, SQLException {BigDecimal valueInUSD = resultSet. getBigDecimal (names [0]); // Deferred check after first readif (resultSet. wasNull () return null; Currency userCurrency = User. getPreferences (). getCurrency (); MonetaryAmount amount = new MonetaryAmount (valueInUSD, "USD"); return amount. convertize (userCurrency);} // write the attribute value to JDBC's PreparedStatementpublic void nullSafeSet (PreparedStatement pstmt, Object value, int index) throws HibernateException, SQLException {if (null = value) {pstmt. setNull (index, BigDecimalType. INSTANCE. sqlType ();} else {MonetaryAmount anyCurrency = (MonetaryAmount) value; MonetaryAmount amountInUSD = MonetaryAmount. convert (anyCurrency, Currency. getInstance ("USD"); pstmt. setBigDecimal (index, anyCurrency. getAmount ());}}}
The initialPrice attribute of the ing Item is as follows:
 
Note that you put the customized user type into the persistence package. It is part of the persistence layer of the application, not part of the domain model or business layer.
To use custom types in annotations, you must add a Hibernate extension:
@org.hibernate.annotations.Type(    type = "persistence.MonetaryAmountUserType")@Column(name = "INITIAL_PRICE")private MonetaryAmount initialPrice;
This is one of the simplest conversions that can be executed by UserType. More complex things are also possible. The custom ing type can be verified. It can read and write data to an LDAP directory. It can even obtain persistent objects from different databases.
Hibernate does not know any information about the independent attributes of MonetaryAmount. All it knows is the custom type class and column name. The Hibernate query engine does not know how to query amount or specific currency.
If you need all the functions of Hibernate query, write CompositeUserType. This (somewhat complex) interface exposes the attributes of MonetaryAmount to Hibernate for query. Now, we use this more flexible custom interface to map it to two columns, which actually generates the equivalence of component ing.

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.