Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
97 changes: 97 additions & 0 deletions src/main/java/com/karakays/hibernate/array/BaseEnumArrayType.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
/**
* Copyright (C) 2018 Selçuk Karakayalı (skarakayali@gmail.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.karakays.hibernate.array;

import org.hibernate.HibernateException;
import org.hibernate.usertype.ParameterizedType;
import org.hibernate.usertype.UserType;

import java.io.Serializable;
import java.sql.Types;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Properties;

/**
* Base class for array type that persists a list of custom enums
*
* @author Selçuk Karakayalı
*/
public abstract class BaseEnumArrayType implements UserType, ParameterizedType {
protected final int[] arrayTypes = new int[] { Types.ARRAY };

protected Class<Enum<?>> mappedClass;

protected void setMappedClass(Class<Enum<?>> mappedClass) {
this.mappedClass = mappedClass;
}

protected Class<Enum<?>> getMappedClass() {
return mappedClass;
}

public int[] sqlTypes() {
return arrayTypes;
}

public Class<List> returnedClass() {
return List.class;
}

public boolean equals(Object x, Object y) throws HibernateException {
return Objects.equals(x, y);
}

public int hashCode(Object x) throws HibernateException {
return x == null ? 0 : x.hashCode();
}

public Object deepCopy(Object value) throws HibernateException {
if (value == null) {
return null;
}

return new ArrayList<>((List<Enum<?>>) value);
}

public boolean isMutable() {
return false;
}

public Serializable disassemble(Object value) throws HibernateException {
return (Serializable) value;
}

public Object assemble(Serializable cached, Object owner) throws HibernateException {
return cached;
}

public Object replace(Object original, Object target, Object owner) throws HibernateException {
return original;
}

public void setParameterValues(Properties parameters) {
if (parameters.containsKey("enumClass")) {
String enumClassName = parameters.getProperty("enumClass");
try {
setMappedClass((Class<Enum<?>>) Class.forName(enumClassName));
} catch (ClassNotFoundException e) {
throw new HibernateException("Specified enum class could not be found", e);
}
}
}
}
86 changes: 6 additions & 80 deletions src/main/java/com/karakays/hibernate/array/EnumArrayType.java
Original file line number Diff line number Diff line change
Expand Up @@ -15,85 +15,22 @@
*/
package com.karakays.hibernate.array;

import java.io.Serializable;
import org.hibernate.HibernateException;
import org.hibernate.engine.spi.SharedSessionContractImplementor;

import java.sql.Array;
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 java.util.Properties;

import org.hibernate.HibernateException;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.usertype.ParameterizedType;
import org.hibernate.usertype.UserType;

/**
* Array type that persists a list of custom enums
* Array type that persists a list of custom enums as string
*
* @author Selçuk Karakayalı
*/
public class EnumArrayType implements UserType, ParameterizedType {
private final int[] arrayTypes = new int[] { Types.ARRAY };

private Class<Enum<?>> mappedClass;

protected void setMappedClass(Class<Enum<?>> mappedClass) {
this.mappedClass = mappedClass;
}

protected Class<Enum<?>> getMappedClass() {
return mappedClass;
}

public int[] sqlTypes() {
return arrayTypes;
}

public Class<List> returnedClass() {
return List.class;
}

public boolean equals(Object x, Object y) throws HibernateException {
return x == null ? y == null : x.equals(y);
}

public int hashCode(Object x) throws HibernateException {
return x == null ? 0 : x.hashCode();
}

public Object deepCopy(Object value) throws HibernateException {
if (value == null) {
return null;
}

List<Enum<?>> list = (List<Enum<?>>) value;
ArrayList<Enum<?>> clone = new ArrayList<Enum<?>>();
for (Enum<?> intOn : list) {
clone.add(intOn);
}

return clone;
}

public boolean isMutable() {
return false;
}

public Serializable disassemble(Object value) throws HibernateException {
return (Serializable) value;
}

public Object assemble(Serializable cached, Object owner) throws HibernateException {
return cached;
}

public Object replace(Object original, Object target, Object owner) throws HibernateException {
return original;
}

public class EnumArrayType extends BaseEnumArrayType {
public Object nullSafeGet(ResultSet rs, String[] names, SharedSessionContractImplementor session, Object owner)
throws HibernateException, SQLException {
if (names != null && names.length > 0 && rs != null && rs.getArray(names[0]) != null) {
Expand All @@ -113,22 +50,11 @@ public void nullSafeSet(PreparedStatement st, Object value, int index, SharedSes
throws HibernateException, SQLException {
if (value != null && st != null) {
List<Enum<?>> list = (List<Enum<?>>) value;
String[] castObject = (String[]) list.stream().map(e -> e.name()).toArray(String[]::new);
String[] castObject = list.stream().map(Enum::name).toArray(String[]::new);
Array array = session.connection().createArrayOf("text", castObject);
st.setArray(index, array);
} else {
st.setNull(index, arrayTypes[0]);
}
}

public void setParameterValues(Properties parameters) {
if (parameters.containsKey("enumClass")) {
String enumClassName = parameters.getProperty("enumClass");
try {
setMappedClass((Class<Enum<?>>) Class.forName(enumClassName));
} catch (ClassNotFoundException e) {
throw new HibernateException("Specified enum class could not be found", e);
}
}
}
}
70 changes: 70 additions & 0 deletions src/main/java/com/karakays/hibernate/array/EnumIntArrayType.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
/**
* Copyright (C) 2018 Selçuk Karakayalı (skarakayali@gmail.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.karakays.hibernate.array;

import org.hibernate.HibernateException;
import org.hibernate.engine.spi.SharedSessionContractImplementor;

import java.sql.Array;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
* Array type that persists a list of custom enums as integer
*
* @author Selçuk Karakayalı
*/
public class EnumIntArrayType extends BaseEnumArrayType {
public Object nullSafeGet(ResultSet rs, String[] names, SharedSessionContractImplementor session, Object owner)
throws HibernateException, SQLException {
if (names != null && names.length > 0 && rs != null && rs.getArray(names[0]) != null) {
Integer[] values = ((Integer[]) rs.getArray(names[0]).getArray());

List<Enum<?>> enumList = new ArrayList<>();

for (Integer value : values) {
for (Enum<?> enumConstant : mappedClass.getEnumConstants()) {
if (enumConstant.ordinal() == value) {
enumList.add(enumConstant);
}
}
}
return enumList;
}
return null;
}

public void nullSafeSet(PreparedStatement st, Object value, int index, SharedSessionContractImplementor session)
throws HibernateException, SQLException {
if (value != null && st != null) {
List<Enum<?>> list = (List<Enum<?>>) value;
Integer[] castObject = list.stream().map(e -> {
if (e == null) {
return null;
} else {
return e.ordinal();
}
}).toArray(Integer[]::new);
Array array = session.connection().createArrayOf("int", castObject);
st.setArray(index, array);
} else {
st.setNull(index, arrayTypes[0]);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -15,14 +15,8 @@
*/
package com.karakays.hibernate.array;

import static org.hamcrest.CoreMatchers.nullValue;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.greaterThan;
import static org.hamcrest.Matchers.hasItems;

import java.io.Serializable;
import java.util.Arrays;

import com.karakays.hibernate.array.domain.Item;
import com.karakays.hibernate.array.domain.User;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.Metadata;
Expand All @@ -34,8 +28,13 @@
import org.junit.BeforeClass;
import org.junit.Test;

import com.karakays.hibernate.array.domain.Item;
import com.karakays.hibernate.array.domain.User;
import java.io.Serializable;
import java.util.Arrays;

import static org.hamcrest.CoreMatchers.nullValue;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.greaterThan;
import static org.hamcrest.Matchers.hasItems;

public class HibernateCustomTypeTest {
private static SessionFactory sessionFactory;
Expand Down Expand Up @@ -108,29 +107,34 @@ public void shouldLoadUser() {
User loadedUser = (User) load(User.class, user1.getId());

assertThat(loadedUser.getBadges(), hasItems(User.Badge.MASTER));
assertThat(loadedUser.getBadgesAsInt(), hasItems(User.Badge.MASTER));
}

@Test
public void shouldUpdateProperty() {
Item item = (Item) load(Item.class, item2);
item.setProperties(Arrays.asList(Item.Property.ALL));

item.setPropertiesAsInt(Arrays.asList(Item.Property.ALL));

save(item);
item = load(Item.class, item2);

assertThat(item.getProperties(), hasItems(Item.Property.ALL));
assertThat(item.getPropertiesAsInt(), hasItems(Item.Property.ALL));
}

@Test
public void shouldDeleteProperty() {
Item item = (Item) load(Item.class, item2);
item.setProperties(null);;
item.setProperties(null);
item.setPropertiesAsInt(null);

update(item);

item = (Item) load(Item.class, item2);

assertThat(item.getProperties(), nullValue());
assertThat(item.getPropertiesAsInt(), nullValue());
}

@SuppressWarnings("unchecked")
Expand Down
Loading