Advertisement
Guest User

Untitled

a guest
May 24th, 2018
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 10.03 KB | None | 0 0
  1. package com.martinyuk.travelagency.domain;
  2.  
  3. import java.io.Serializable;
  4. import java.lang.reflect.InvocationTargetException;
  5. import java.lang.reflect.Method;
  6.  
  7. import org.hibernate.mapping.PersistentClass;
  8. import org.hibernate.tuple.Instantiator;
  9. import org.hibernate.tuple.entity.EntityMetamodel;
  10. import org.hibernate.tuple.entity.PojoEntityTuplizer;
  11.  
  12. public class EnumTuplizer extends PojoEntityTuplizer {
  13.  
  14.     public EnumTuplizer(EntityMetamodel entityMetamodel, PersistentClass mappedEntity) {
  15.         super(entityMetamodel, mappedEntity);
  16.     }
  17.  
  18.     @Override
  19.     @SuppressWarnings(value = { "unchecked", "rawtypes"})
  20.     protected Instantiator buildInstantiator(EntityMetamodel entityMetamodel, PersistentClass persistentClass) {
  21.         return new Instantiator() {
  22.             @Override
  23.             public Object instantiate(Serializable id) {
  24.                 try {
  25.                     Class enumClass = getMappedClass();
  26.                     String identifierMethodName = EnumUserType.DEFAULT_CODE_VALUE_METHOD_NAME;
  27.                     Method codeValueMethod = enumClass.getMethod(identifierMethodName, new Class[0]);
  28.                     Class<?> codeValueType = codeValueMethod.getReturnType();
  29.                     String valueOfMethodName = EnumUserType.DEFAULT_FROM_VALUE_METHOD_NAME;
  30.                     Method fromValueMethod = enumClass.getMethod(valueOfMethodName, new Class[] { codeValueType });
  31.                     return fromValueMethod.invoke(enumClass, id);
  32.                 } catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
  33.                     throw new AssertionError(e);
  34.                 }
  35.             }
  36.  
  37.             @Override
  38.             public Object instantiate() {
  39.                 throw new UnsupportedOperationException();
  40.             }
  41.  
  42.             @Override
  43.             public boolean isInstance(Object object) {
  44.                 throw new UnsupportedOperationException();
  45.             }
  46.         };
  47.     }
  48. }
  49.  
  50. package com.martinyuk.travelagency.domain;
  51.  
  52. import java.io.Serializable;
  53. import java.lang.reflect.Method;
  54. import java.sql.PreparedStatement;
  55. import java.sql.ResultSet;
  56. import java.sql.SQLException;
  57. import java.sql.Types;
  58. import java.util.Properties;
  59.  
  60. import org.apache.commons.lang.ObjectUtils;
  61. import org.hibernate.HibernateException;
  62. import org.hibernate.engine.spi.SharedSessionContractImplementor;
  63. import org.hibernate.type.IntegerType;
  64. import org.hibernate.usertype.ParameterizedType;
  65. import org.hibernate.usertype.UserType;
  66.  
  67. public class EnumUserType<E> implements UserType, ParameterizedType {
  68.     public static final String DEFAULT_CODE_VALUE_METHOD_NAME = "getId";
  69.     public static final String DEFAULT_FROM_VALUE_METHOD_NAME = "fromValue";
  70.     private Method codeValueMethod;
  71.     private Method fromValueMethod;
  72.     private Class<?> codeValueType;
  73.     private Class<E> enumClass;
  74.  
  75.     public EnumUserType(){}
  76.  
  77.     @Override
  78.     @SuppressWarnings("unchecked")
  79.     public void setParameterValues(Properties parameters) {
  80.         String enumClassName = parameters.getProperty("enumClass");
  81.         try {
  82.             enumClass =  (Class<E>) Class.forName(enumClassName).asSubclass(Enum.class);
  83.         } catch (ClassNotFoundException e) {
  84.             throw new HibernateException("Enum class not found", e);
  85.         }
  86.         String identifierMethodName = parameters.getProperty("codeValueMethod", DEFAULT_CODE_VALUE_METHOD_NAME);
  87.         try {
  88.             codeValueMethod = enumClass.getMethod(identifierMethodName, new Class[0]);
  89.             codeValueType = codeValueMethod.getReturnType();
  90.         } catch (Exception e) {
  91.             throw new HibernateException("Failed to obtain codeValue method. Setting default method name", e);
  92.         }
  93.         String valueOfMethodName = parameters.getProperty("fromValueMethod", DEFAULT_FROM_VALUE_METHOD_NAME);
  94.         try {
  95.             fromValueMethod = enumClass.getMethod(valueOfMethodName, new Class[] { codeValueType });
  96.         } catch (Exception e) {
  97.             throw new HibernateException("Failed to obtain fromValue method. Setting default method name", e);
  98.         }
  99.     }
  100.  
  101.     @Override
  102.     public Class<E> returnedClass() {
  103.         return enumClass;
  104.     }
  105.  
  106.     @Override
  107.     public int[] sqlTypes() {
  108.         return new int[] { IntegerType.INSTANCE.sqlType() };
  109.     }
  110.  
  111.     @Override
  112.     public boolean isMutable() {
  113.         return false;
  114.     }
  115.  
  116.     @Override
  117.     public boolean equals(Object x, Object y) throws HibernateException {
  118.         return ObjectUtils.equals(x, y);
  119.     }
  120.  
  121.     @Override
  122.     public int hashCode(Object x) throws HibernateException {
  123.         assert (x != null);
  124.         return x.hashCode();
  125.     }
  126.  
  127.     @Override
  128.     public Object nullSafeGet(ResultSet rs, String[] names, SharedSessionContractImplementor session, Object owner) throws HibernateException, SQLException {
  129.         try {
  130.             String propertyValue = rs.getString(names[0]);
  131.             Integer propertyNumericValue;
  132.             try {
  133.                 propertyNumericValue = Integer.valueOf(propertyValue);
  134.             } catch (NumberFormatException e) {
  135.                 return null;
  136.             }
  137.             return fromValueMethod.invoke(enumClass, propertyNumericValue);
  138.         } catch (Exception e) {
  139.             e.printStackTrace();
  140.             throw new HibernateException("Exception while invoking valueOf method '" + fromValueMethod.getName() + "' of " + "enumeration class '" + enumClass + "'", e);
  141.         }
  142.     }
  143.  
  144.     @Override
  145.     public void nullSafeSet(PreparedStatement st, Object value, int index, SharedSessionContractImplementor session) throws HibernateException, SQLException {
  146.         try {
  147.             if (null == value) {
  148.                 st.setNull(index, Types.INTEGER);
  149.             } else {
  150.                 Object identifier = codeValueMethod.invoke(value, new Object[0]);
  151.                 st.setInt(index, (Integer) identifier);
  152.             }
  153.         } catch (Exception e) {
  154.             e.printStackTrace();
  155.             throw new HibernateException("Exception while invoking identifier method '" + codeValueMethod.getName() + "' of " + "enumeration class '" + enumClass + "'", e);
  156.         }
  157.     }
  158.  
  159.     @Override
  160.     public Object deepCopy(Object value) throws HibernateException {
  161.         return value;
  162.     }
  163.  
  164.     @Override
  165.     public Object replace(Object original, Object target, Object owner) throws HibernateException {
  166.         return original;
  167.     }
  168.  
  169.     @Override
  170.     public Serializable disassemble(Object value) throws HibernateException {
  171.         return (Serializable) value;
  172.     }
  173.  
  174.     @Override
  175.     public Object assemble(Serializable cached, Object owner) throws HibernateException {
  176.         return cached;
  177.     }
  178.  
  179. }
  180.  
  181. package com.martinyuk.travelagency.domain;
  182.  
  183. import lombok.AccessLevel;
  184. import lombok.NoArgsConstructor;
  185. import org.hibernate.annotations.Tuplizer;
  186.  
  187. import javax.persistence.Column;
  188. import javax.persistence.Entity;
  189. import javax.persistence.Id;
  190. import javax.persistence.Table;
  191.  
  192. @Entity
  193. @Table(name = "tour_type")
  194. @Tuplizer(impl = EnumTuplizer.class)
  195. @NoArgsConstructor(access = AccessLevel.PRIVATE)
  196. public enum TourType {
  197.  
  198.     VACATION(1, "VACATION"),
  199.  
  200.     TRIP(2, "TRIP"),
  201.  
  202.     SHOPPING(3, "SHOPPING");
  203.  
  204.     @Id
  205.     @Column(name = "id_tour_type")
  206.     private long id;
  207.  
  208.     @Column(name = "type")
  209.     private String name;
  210.  
  211.     TourType(long id, String name) {
  212.         this.id = id;
  213.         this.name = name;
  214.     }
  215.  
  216.     public String getName() {
  217.         return name;
  218.     }
  219.  
  220.     public long getId() {
  221.         return id;
  222.     }
  223.  
  224.     public static TourType fromValue(long value) {
  225.         switch ((int)value) {
  226.             case 1: return VACATION;
  227.             case 2: return TRIP;
  228.             case 3: return SHOPPING;
  229.             default: return null;
  230.         }
  231.     }
  232. }
  233.  
  234. package com.martinyuk.travelagency.domain;
  235.  
  236. import lombok.AllArgsConstructor;
  237. import lombok.Data;
  238. import lombok.NoArgsConstructor;
  239. import org.hibernate.annotations.Parameter;
  240. import org.hibernate.annotations.Type;
  241.  
  242. import javax.persistence.CascadeType;
  243. import javax.persistence.Column;
  244. import javax.persistence.Entity;
  245. import javax.persistence.EnumType;
  246. import javax.persistence.Enumerated;
  247. import javax.persistence.FetchType;
  248. import javax.persistence.ForeignKey;
  249. import javax.persistence.GeneratedValue;
  250. import javax.persistence.GenerationType;
  251. import javax.persistence.Id;
  252. import javax.persistence.JoinColumn;
  253. import javax.persistence.JoinTable;
  254. import javax.persistence.ManyToMany;
  255. import javax.persistence.ManyToOne;
  256. import javax.persistence.NamedQuery;
  257. import javax.persistence.OneToMany;
  258. import javax.persistence.OneToOne;
  259. import javax.persistence.PrimaryKeyJoinColumn;
  260. import javax.persistence.SecondaryTable;
  261. import javax.persistence.Table;
  262. import java.math.BigDecimal;
  263. import java.time.LocalDate;
  264.  
  265. @Data
  266. @Entity
  267. @Table(name = "tour")
  268. @NoArgsConstructor
  269. @AllArgsConstructor
  270. @NamedQuery(name = "Tour.findAll", query = "FROM Tour")
  271. public class Tour {
  272.     @Id
  273.     @GeneratedValue(strategy = GenerationType.IDENTITY)
  274.     @Column(name = "id_tour", nullable = false, insertable = false, updatable = false)
  275.     private long id;
  276.  
  277.     @Column(name = "photo", nullable = false)
  278.     private byte[] photo;
  279.  
  280.     @Column(name = "date", nullable = false)
  281.     private LocalDate date;
  282.  
  283.     @Column(name = "duration", nullable = false)
  284.     private int duration;
  285.  
  286.     @ManyToOne(optional = false, cascade = CascadeType.MERGE)
  287.     @JoinColumn(name = "hotel_id_fk", nullable = false)
  288.     private Hotel hotel;
  289.  
  290.     @ManyToOne(optional = false, cascade = CascadeType.MERGE)
  291.     @JoinColumn(name = "tour_type_id_fk", nullable = false)
  292.     @Type(type = "com.martinyuk.travelagency.domain.EnumUserType", parameters = @Parameter(name = "type", value = "com.martinyuk.travelagency.domain.TourType"))
  293.     private TourType tourType;
  294.  
  295.     @Column(name = "description", nullable = false)
  296.     private String description;
  297.  
  298.     @Column(name = "cost", nullable = false)
  299.     private BigDecimal cost;
  300.  
  301. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement