Merge branch 'eugenp:master' into master

This commit is contained in:
Sam
2023-05-14 12:27:30 -04:00
committed by technoddy
2353 changed files with 30469 additions and 7799 deletions
+2 -2
View File
@@ -74,9 +74,9 @@
</build>
<properties>
<activejdbc.version>2.0</activejdbc.version>
<activejdbc.version>3.4-j11</activejdbc.version>
<environments>development.test,development</environments>
<mysql.connector.version>5.1.34</mysql.connector.version>
<mysql.connector.version>8.0.32</mysql.connector.version>
</properties>
</project>
@@ -4,6 +4,7 @@ package com.baeldung;
import com.baeldung.model.Employee;
import com.baeldung.model.Role;
import org.javalite.activejdbc.Base;
import org.javalite.activejdbc.DB;
import org.javalite.activejdbc.LazyList;
import org.javalite.activejdbc.Model;
@@ -11,8 +12,7 @@ public class ActiveJDBCApp
{
public static void main( String[] args )
{
try {
Base.open();
try(final DB open = Base.open()) {
ActiveJDBCApp app = new ActiveJDBCApp();
app.create();
app.update();
@@ -52,14 +52,21 @@
<artifactId>spring-boot-starter</artifactId>
<version>${springframework.boot.spring-boot-starter.version}</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql-connector.version}</version>
<scope>runtime</scope>
</dependency>
</dependencies>
<properties>
<commons-dbcp2.version>2.4.0</commons-dbcp2.version>
<HikariCP.version>3.2.0</HikariCP.version>
<c3p0.version>0.9.5.2</c3p0.version>
<springframework.boot.spring-boot-starter.version>1.5.8.RELEASE</springframework.boot.spring-boot-starter.version>
<springframework.spring-web.version>4.3.4.RELEASE</springframework.spring-web.version>
<commons-dbcp2.version>2.9.0</commons-dbcp2.version>
<HikariCP.version>5.0.1</HikariCP.version>
<c3p0.version>0.9.5.5</c3p0.version>
<springframework.boot.spring-boot-starter.version>3.0.4</springframework.boot.spring-boot-starter.version>
<springframework.spring-web.version>6.0.6</springframework.spring-web.version>
<mysql-connector.version>8.0.32</mysql-connector.version>
</properties>
</project>
@@ -1,13 +1,14 @@
package com.baeldung.jdbcmetadata;
import org.apache.log4j.Logger;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class DatabaseConfig {
private static final Logger LOG = Logger.getLogger(DatabaseConfig.class);
private static final Logger LOG = LoggerFactory.getLogger(DatabaseConfig.class);
private Connection connection;
@@ -17,7 +18,7 @@ public class DatabaseConfig {
String url = "jdbc:h2:mem:testdb";
connection = DriverManager.getConnection(url, "sa", "");
} catch (ClassNotFoundException | SQLException e) {
LOG.error(e);
LOG.error(e.getMessage());
}
}
@@ -35,7 +36,7 @@ public class DatabaseConfig {
connection.createStatement().executeUpdate("create table CUSTOMER (ID int primary key auto_increment, NAME VARCHAR(45))");
connection.createStatement().executeUpdate("create table CUST_ADDRESS (ID VARCHAR(36), CUST_ID int, ADDRESS VARCHAR(45), FOREIGN KEY (CUST_ID) REFERENCES CUSTOMER(ID))");
} catch (SQLException e) {
LOG.error(e);
LOG.error(e.getMessage());
}
}
@@ -43,7 +44,7 @@ public class DatabaseConfig {
try {
connection.createStatement().executeUpdate("CREATE VIEW CUSTOMER_VIEW AS SELECT * FROM CUSTOMER");
} catch (SQLException e) {
LOG.error(e);
LOG.error(e.getMessage());
}
}
}
@@ -1,12 +1,13 @@
package com.baeldung.jdbcmetadata;
import org.apache.log4j.Logger;
import java.sql.SQLException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class JdbcMetadataApplication {
private static final Logger LOG = Logger.getLogger(JdbcMetadataApplication.class);
private static final Logger LOG = LoggerFactory.getLogger(JdbcMetadataApplication.class);
public static void main(String[] args) {
DatabaseConfig databaseConfig = new DatabaseConfig();
@@ -5,10 +5,6 @@ import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import javax.sql.rowset.JdbcRowSet;
import javax.sql.rowset.RowSetFactory;
import javax.sql.rowset.RowSetProvider;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.Configuration;
@@ -7,8 +7,6 @@ import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import com.sun.rowset.*;
import javax.sql.rowset.CachedRowSet;
import javax.sql.rowset.FilteredRowSet;
import javax.sql.rowset.JdbcRowSet;
@@ -25,7 +23,7 @@ public class JdbcRowsetApplication {
public static void main(String[] args) throws Exception {
SpringApplication.run(JdbcRowsetApplication.class, args);
Statement stmt = null;
Statement stmt;
try {
Connection conn = DatabaseConfiguration.geth2Connection();
@@ -41,8 +39,7 @@ public class JdbcRowsetApplication {
DatabaseConfiguration.initDatabase(stmt);
// JdbcRowSet Example
String sql = "SELECT * FROM customers";
JdbcRowSet jdbcRS;
jdbcRS = new JdbcRowSetImpl(conn);
JdbcRowSet jdbcRS = RowSetProvider.newFactory().createJdbcRowSet();
jdbcRS.setType(ResultSet.TYPE_SCROLL_INSENSITIVE);
jdbcRS.setCommand(sql);
jdbcRS.execute();
@@ -58,7 +55,8 @@ public class JdbcRowsetApplication {
String username = "sa";
String password = "";
String url = "jdbc:h2:mem:testdb";
CachedRowSet crs = new CachedRowSetImpl();
RowSetFactory aFactory = RowSetProvider.newFactory();
CachedRowSet crs = aFactory.createCachedRowSet();
crs.setUsername(username);
crs.setPassword(password);
crs.setUrl(url);
@@ -74,7 +72,7 @@ public class JdbcRowsetApplication {
}
// WebRowSet example
WebRowSet wrs = new WebRowSetImpl();
WebRowSet wrs = RowSetProvider.newFactory().createWebRowSet();
wrs.setUsername(username);
wrs.setPassword(password);
wrs.setUrl(url);
@@ -84,14 +82,14 @@ public class JdbcRowsetApplication {
wrs.writeXml(ostream);
// JoinRowSet example
CachedRowSetImpl customers = new CachedRowSetImpl();
CachedRowSet customers = aFactory.createCachedRowSet();
customers.setUsername(username);
customers.setPassword(password);
customers.setUrl(url);
customers.setCommand(sql);
customers.execute();
CachedRowSetImpl associates = new CachedRowSetImpl();
CachedRowSet associates = aFactory.createCachedRowSet();
associates.setUsername(username);
associates.setPassword(password);
associates.setUrl(url);
@@ -99,7 +97,7 @@ public class JdbcRowsetApplication {
associates.setCommand(associatesSQL);
associates.execute();
JoinRowSet jrs = new JoinRowSetImpl();
JoinRowSet jrs = RowSetProvider.newFactory().createJoinRowSet();
final String ID = "id";
final String NAME = "name";
jrs.addRowSet(customers, ID);
@@ -19,11 +19,6 @@ import javax.sql.rowset.WebRowSet;
import org.junit.Before;
import org.junit.Test;
import com.sun.rowset.CachedRowSetImpl;
import com.sun.rowset.JdbcRowSetImpl;
import com.sun.rowset.JoinRowSetImpl;
import com.sun.rowset.WebRowSetImpl;
public class JdbcRowSetLiveTest {
Statement stmt = null;
String username = "sa";
@@ -51,9 +46,10 @@ public class JdbcRowSetLiveTest {
public void createJdbcRowSet_SelectCustomers_ThenCorrect() throws Exception {
String sql = "SELECT * FROM customers";
JdbcRowSet jdbcRS;
Connection conn = DatabaseConfiguration.geth2Connection();
jdbcRS = new JdbcRowSetImpl(conn);
JdbcRowSet jdbcRS = RowSetProvider.newFactory().createJdbcRowSet();
jdbcRS.setUrl("jdbc:h2:mem:testdb");
jdbcRS.setUsername("sa");
jdbcRS.setPassword("");
jdbcRS.setType(ResultSet.TYPE_SCROLL_INSENSITIVE);
jdbcRS.setCommand(sql);
jdbcRS.execute();
@@ -71,7 +67,7 @@ public class JdbcRowSetLiveTest {
@Test
public void createCachedRowSet_DeleteRecord_ThenCorrect() throws Exception {
CachedRowSet crs = new CachedRowSetImpl();
CachedRowSet crs = RowSetProvider.newFactory().createCachedRowSet();
crs.setUsername(username);
crs.setPassword(password);
crs.setUrl(url);
@@ -91,7 +87,7 @@ public class JdbcRowSetLiveTest {
@Test
public void createWebRowSet_SelectCustomers_WritetoXML_ThenCorrect() throws SQLException, IOException {
WebRowSet wrs = new WebRowSetImpl();
WebRowSet wrs = RowSetProvider.newFactory().createWebRowSet();
wrs.setUsername(username);
wrs.setPassword(password);
wrs.setUrl(url);
@@ -105,14 +101,14 @@ public class JdbcRowSetLiveTest {
@Test
public void createCachedRowSets_DoJoinRowSet_ThenCorrect() throws Exception {
CachedRowSetImpl customers = new CachedRowSetImpl();
CachedRowSet customers = RowSetProvider.newFactory().createCachedRowSet();
customers.setUsername(username);
customers.setPassword(password);
customers.setUrl(url);
customers.setCommand(sql);
customers.execute();
CachedRowSetImpl associates = new CachedRowSetImpl();
CachedRowSet associates = RowSetProvider.newFactory().createCachedRowSet();
associates.setUsername(username);
associates.setPassword(password);
associates.setUrl(url);
@@ -120,7 +116,7 @@ public class JdbcRowSetLiveTest {
associates.setCommand(associatesSQL);
associates.execute();
JoinRowSet jrs = new JoinRowSetImpl();
JoinRowSet jrs = RowSetProvider.newFactory().createJoinRowSet();
final String ID = "id";
final String NAME = "name";
jrs.addRowSet(customers, ID);
@@ -1,9 +1,10 @@
package com.baeldung.spring.jdbc;
import org.apache.log4j.Logger;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.sql.CallableStatement;
import java.sql.Connection;
@@ -24,7 +25,7 @@ import static org.junit.Assert.assertTrue;
public class JdbcLiveTest {
private static final Logger LOG = Logger.getLogger(JdbcLiveTest.class);
private static final Logger LOG = LoggerFactory.getLogger(JdbcLiveTest.class);
private Connection con;
@@ -13,7 +13,6 @@ import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import org.apache.log4j.Logger;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.FixMethodOrder;
@@ -25,8 +24,6 @@ import junit.framework.Assert;
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class ResultSetLiveTest {
private static final Logger logger = Logger.getLogger(ResultSetLiveTest.class);
private final Employee expectedEmployee1 = new Employee(1, "John", 1000.0, "Developer");
private final Employee updatedEmployee1 = new Employee(1, "John", 1100.0, "Developer");
+1 -1
View File
@@ -33,7 +33,7 @@
</dependencies>
<properties>
<hbase.version>1.3.1</hbase.version>
<hbase.version>2.5.3</hbase.version>
</properties>
</project>
@@ -1,7 +1,5 @@
package com.baeldung.hbase;
import com.google.protobuf.ServiceException;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hbase.HBaseConfiguration;
@@ -13,11 +11,11 @@ import java.io.IOException;
//install hbase locally & hbase master start
public class HbaseClientExample {
public static void main(String[] args) throws IOException, ServiceException {
public static void main(String[] args) throws IOException {
new HbaseClientExample().connect();
}
private void connect() throws IOException, ServiceException {
private void connect() throws IOException {
Configuration config = HBaseConfiguration.create();
String path = this.getClass().getClassLoader().getResource("hbase-site.xml").getPath();
@@ -25,7 +23,7 @@ public class HbaseClientExample {
config.addResource(new Path(path));
try {
HBaseAdmin.checkHBaseAvailable(config);
HBaseAdmin.available(config);
} catch (MasterNotRunningException e) {
System.out.println("HBase is not running." + e.getMessage());
return;
@@ -10,3 +10,4 @@ This module contains articles about Annotations used in Hibernate.
- [Hibernate @WhereJoinTable Annotation](https://www.baeldung.com/hibernate-wherejointable)
- [Usage of the Hibernate @LazyCollection Annotation](https://www.baeldung.com/hibernate-lazycollection)
- [@Immutable in Hibernate](https://www.baeldung.com/hibernate-immutable)
- [Hibernate @CreationTimestamp and @UpdateTimestamp](https://www.baeldung.com/hibernate-creationtimestamp-updatetimestamp)
@@ -76,13 +76,18 @@
<version>${org.springframework.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.hypersistence</groupId>
<artifactId>hypersistence-utils-hibernate-60</artifactId>
<version>3.3.1</version>
</dependency>
</dependencies>
<properties>
<!-- Spring -->
<org.springframework.version>5.0.2.RELEASE</org.springframework.version>
<org.springframework.data.version>1.10.6.RELEASE</org.springframework.data.version>
<hibernate-core.version>5.6.7.Final</hibernate-core.version>
<org.springframework.version>6.0.6</org.springframework.version>
<org.springframework.data.version>3.0.3</org.springframework.data.version>
<hibernate-core.version>6.1.7.Final</hibernate-core.version>
<maven.deploy.skip>true</maven.deploy.skip>
<tomcat-dbcp.version>9.0.0.M26</tomcat-dbcp.version>
</properties>
@@ -0,0 +1,57 @@
package com.baeldung.hibernate.creationupdatetimestamp.model;
import java.time.Instant;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.Id;
import org.hibernate.annotations.CreationTimestamp;
import org.hibernate.annotations.UpdateTimestamp;
@Entity
public class Book {
@Id
@GeneratedValue
private Long id;
private String title;
@CreationTimestamp
private Instant createdOn;
@UpdateTimestamp
private Instant lastUpdatedOn;
public Book() {
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Instant getCreatedOn() {
return createdOn;
}
public void setCreatedOn(Instant createdOn) {
this.createdOn = createdOn;
}
public Instant getLastUpdatedOn() {
return lastUpdatedOn;
}
public void setLastUpdatedOn(Instant lastUpdatedOn) {
this.lastUpdatedOn = lastUpdatedOn;
}
}
@@ -1,11 +1,11 @@
package com.baeldung.hibernate.customtypes;
import org.hibernate.HibernateException;
import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.type.IntegerType;
import org.hibernate.type.StringType;
import org.hibernate.type.Type;
import org.hibernate.metamodel.spi.ValueAccess;
import org.hibernate.usertype.CompositeUserType;
import org.hibernate.usertype.UserType;
import java.io.Serializable;
import java.sql.PreparedStatement;
@@ -14,74 +14,51 @@ import java.sql.SQLException;
import java.sql.Types;
import java.util.Objects;
public class AddressType implements CompositeUserType {
public class AddressType implements CompositeUserType<Address>, UserType<Address> {
@Override
public String[] getPropertyNames() {
return new String[]{"addressLine1", "addressLine2",
"city", "country", "zipcode"};
}
@Override
public Type[] getPropertyTypes() {
return new Type[]{StringType.INSTANCE, StringType.INSTANCE,
StringType.INSTANCE, StringType.INSTANCE, IntegerType.INSTANCE};
}
@Override
public Object getPropertyValue(Object component, int property) throws HibernateException {
Address empAdd = (Address) component;
public Object getPropertyValue(Address component, int property) throws HibernateException {
switch (property) {
case 0:
return empAdd.getAddressLine1();
return component.getAddressLine1();
case 1:
return empAdd.getAddressLine2();
return component.getAddressLine2();
case 2:
return empAdd.getCity();
return component.getCity();
case 3:
return empAdd.getCountry();
return component.getCountry();
case 4:
return Integer.valueOf(empAdd.getZipCode());
return component.getZipCode();
default:
throw new IllegalArgumentException(property +
" is an invalid property index for class type " +
component.getClass().getName());
}
throw new IllegalArgumentException(property +
" is an invalid property index for class type " +
component.getClass().getName());
}
@Override
public void setPropertyValue(Object component, int property, Object value) throws HibernateException {
Address empAdd = (Address) component;
switch (property) {
case 0:
empAdd.setAddressLine1((String) value);
case 1:
empAdd.setAddressLine2((String) value);
case 2:
empAdd.setCity((String) value);
case 3:
empAdd.setCountry((String) value);
case 4:
empAdd.setZipCode((Integer) value);
}
throw new IllegalArgumentException(property +
" is an invalid property index for class type " +
component.getClass().getName());
public Address instantiate(ValueAccess values, SessionFactoryImplementor sessionFactory) {
return null;
}
@Override
public Class returnedClass() {
public Class<?> embeddable() {
return Address.class;
}
@Override
public boolean equals(Object x, Object y) throws HibernateException {
public int getSqlType() {
return Types.VARCHAR;
}
@Override
public Class<Address> returnedClass() {
return Address.class;
}
@Override
public boolean equals(Address x, Address y) {
if (x == y)
return true;
@@ -92,57 +69,52 @@ public class AddressType implements CompositeUserType {
}
@Override
public int hashCode(Object x) throws HibernateException {
public int hashCode(Address x) {
return x.hashCode();
}
@Override
public Object nullSafeGet(ResultSet rs, String[] names, SharedSessionContractImplementor session, Object owner) throws HibernateException, SQLException {
public Address nullSafeGet(ResultSet rs, int position, SharedSessionContractImplementor session, Object owner) throws SQLException {
Address empAdd = new Address();
empAdd.setAddressLine1(rs.getString(names[0]));
empAdd.setAddressLine1(rs.getString(position));
if (rs.wasNull())
return null;
empAdd.setAddressLine2(rs.getString(names[1]));
empAdd.setCity(rs.getString(names[2]));
empAdd.setCountry(rs.getString(names[3]));
empAdd.setZipCode(rs.getInt(names[4]));
empAdd.setAddressLine2(rs.getString(position));
empAdd.setCity(rs.getString(position));
empAdd.setCountry(rs.getString(position));
empAdd.setZipCode(rs.getInt(position));
return empAdd;
}
@Override
public void nullSafeSet(PreparedStatement st, Object value, int index, SharedSessionContractImplementor session) throws HibernateException, SQLException {
public void nullSafeSet(PreparedStatement st, Address value, int index, SharedSessionContractImplementor session) throws SQLException {
if (Objects.isNull(value))
st.setNull(index, Types.VARCHAR);
else {
Address empAdd = (Address) value;
st.setString(index, empAdd.getAddressLine1());
st.setString(index + 1, empAdd.getAddressLine2());
st.setString(index + 2, empAdd.getCity());
st.setString(index + 3, empAdd.getCountry());
st.setInt(index + 4, empAdd.getZipCode());
st.setString(index, value.getAddressLine1());
st.setString(index + 1, value.getAddressLine2());
st.setString(index + 2, value.getCity());
st.setString(index + 3, value.getCountry());
st.setInt(index + 4, value.getZipCode());
}
}
@Override
public Object deepCopy(Object value) throws HibernateException {
public Address deepCopy(Address value) {
if (Objects.isNull(value))
return null;
Address oldEmpAdd = (Address) value;
Address newEmpAdd = new Address();
newEmpAdd.setAddressLine1(oldEmpAdd.getAddressLine1());
newEmpAdd.setAddressLine2(oldEmpAdd.getAddressLine2());
newEmpAdd.setCity(oldEmpAdd.getCity());
newEmpAdd.setCountry(oldEmpAdd.getCountry());
newEmpAdd.setZipCode(oldEmpAdd.getZipCode());
newEmpAdd.setAddressLine1(value.getAddressLine1());
newEmpAdd.setAddressLine2(value.getAddressLine2());
newEmpAdd.setCity(value.getCity());
newEmpAdd.setCountry(value.getCountry());
newEmpAdd.setZipCode(value.getZipCode());
return newEmpAdd;
}
@@ -153,17 +125,27 @@ public class AddressType implements CompositeUserType {
}
@Override
public Serializable disassemble(Object value, SharedSessionContractImplementor session) throws HibernateException {
public Serializable disassemble(Address value) {
return (Serializable) deepCopy(value);
}
@Override
public Object assemble(Serializable cached, SharedSessionContractImplementor session, Object owner) throws HibernateException {
return deepCopy(cached);
public Address assemble(Serializable cached, Object owner) {
return deepCopy((Address) cached);
}
@Override
public Object replace(Object original, Object target, SharedSessionContractImplementor session, Object owner) throws HibernateException {
return original;
public Address replace(Address detached, Address managed, Object owner) {
return detached;
}
@Override
public boolean isInstance(Object object, SessionFactoryImplementor sessionFactory) {
return CompositeUserType.super.isInstance(object, sessionFactory);
}
@Override
public boolean isSameClass(Object object, SessionFactoryImplementor sessionFactory) {
return CompositeUserType.super.isSameClass(object, sessionFactory);
}
}
@@ -1,14 +1,14 @@
package com.baeldung.hibernate.customtypes;
import org.hibernate.type.LocalDateType;
import org.hibernate.type.descriptor.WrapperOptions;
import org.hibernate.type.descriptor.java.AbstractTypeDescriptor;
import org.hibernate.type.descriptor.java.ImmutableMutabilityPlan;
import org.hibernate.type.descriptor.java.MutabilityPlan;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
public class LocalDateStringJavaDescriptor extends AbstractTypeDescriptor<LocalDate> {
import io.hypersistence.utils.hibernate.type.array.internal.AbstractArrayTypeDescriptor;
public class LocalDateStringJavaDescriptor extends AbstractArrayTypeDescriptor<LocalDate> {
public static final LocalDateStringJavaDescriptor INSTANCE = new LocalDateStringJavaDescriptor();
@@ -18,12 +18,12 @@ public class LocalDateStringJavaDescriptor extends AbstractTypeDescriptor<LocalD
@Override
public String toString(LocalDate value) {
return LocalDateType.FORMATTER.format(value);
return DateTimeFormatter.ISO_LOCAL_DATE.format(value);
}
@Override
public LocalDate fromString(String string) {
return LocalDate.from(LocalDateType.FORMATTER.parse(string));
public LocalDate fromString(CharSequence string) {
return LocalDate.from( DateTimeFormatter.ISO_LOCAL_DATE.parse(string));
}
@Override
@@ -33,7 +33,7 @@ public class LocalDateStringJavaDescriptor extends AbstractTypeDescriptor<LocalD
return null;
if (String.class.isAssignableFrom(type))
return (X) LocalDateType.FORMATTER.format(value);
return (X) DateTimeFormatter.ISO_LOCAL_DATE.format(value);
throw unknownUnwrap(type);
}
@@ -44,7 +44,7 @@ public class LocalDateStringJavaDescriptor extends AbstractTypeDescriptor<LocalD
return null;
if(String.class.isInstance(value))
return LocalDate.from(LocalDateType.FORMATTER.parse((CharSequence) value));
return LocalDate.from( DateTimeFormatter.ISO_LOCAL_DATE.parse((CharSequence) value));
throw unknownWrap(value.getClass());
}
@@ -2,18 +2,16 @@ package com.baeldung.hibernate.customtypes;
import org.hibernate.dialect.Dialect;
import org.hibernate.type.AbstractSingleColumnStandardBasicType;
import org.hibernate.type.DiscriminatorType;
import org.hibernate.type.descriptor.java.LocalDateJavaDescriptor;
import org.hibernate.type.descriptor.sql.VarcharTypeDescriptor;
import org.hibernate.type.descriptor.jdbc.VarcharJdbcType;
import java.time.LocalDate;
public class LocalDateStringType extends AbstractSingleColumnStandardBasicType<LocalDate> implements DiscriminatorType<LocalDate> {
public class LocalDateStringType extends AbstractSingleColumnStandardBasicType<LocalDate> {
public static final LocalDateStringType INSTANCE = new LocalDateStringType();
public LocalDateStringType() {
super(VarcharTypeDescriptor.INSTANCE, LocalDateStringJavaDescriptor.INSTANCE);
super(VarcharJdbcType.INSTANCE, LocalDateStringJavaDescriptor.INSTANCE);
}
@Override
@@ -21,14 +19,12 @@ public class LocalDateStringType extends AbstractSingleColumnStandardBasicType<L
return "LocalDateString";
}
@Override
public LocalDate stringToObject(String xml) throws Exception {
public LocalDate stringToObject(String xml) {
return fromString(xml);
}
@Override
public String objectToSQLString(LocalDate value, Dialect dialect) throws Exception {
return '\'' + toString(value) + '\'';
public String objectToSQLString(LocalDate value, Dialect dialect) {
return '\'' + LocalDateStringJavaDescriptor.INSTANCE.toString(value) + '\'';
}
}
@@ -1,20 +1,19 @@
package com.baeldung.hibernate.customtypes;
import org.hibernate.annotations.Columns;
import org.hibernate.annotations.CompositeType;
import org.hibernate.annotations.Parameter;
import org.hibernate.annotations.Type;
import org.hibernate.annotations.TypeDef;
import org.hibernate.usertype.UserTypeLegacyBridge;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import jakarta.persistence.AttributeOverride;
import jakarta.persistence.AttributeOverrides;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
import java.time.LocalDate;
@TypeDef(name = "PhoneNumber",
typeClass = PhoneNumberType.class,
defaultForType = PhoneNumber.class)
@Entity
@Table(name = "OfficeEmployee")
public class OfficeEmployee {
@@ -24,25 +23,36 @@ public class OfficeEmployee {
private long id;
@Column
@Type(type = "LocalDateString")
@Type(
value = UserTypeLegacyBridge.class,
parameters = @Parameter(name = UserTypeLegacyBridge.TYPE_NAME_PARAM_KEY, value = "LocalDateString")
)
private LocalDate dateOfJoining;
@Columns(columns = {@Column(name = "country_code"),
@Column(name = "city_code"),
@Column(name = "number")})
@AttributeOverrides({
@AttributeOverride(name = "countryCode", column = @Column(name = "country_code")),
@AttributeOverride(name = "cityCode", column = @Column(name = "city_code")),
@AttributeOverride(name = "number", column = @Column(name = "number"))
})
@Type(value = PhoneNumberType.class)
private PhoneNumber employeeNumber;
@Columns(columns = {@Column(name = "address_line_1"),
@Column(name = "address_line_2"),
@Column(name = "city"), @Column(name = "country"),
@Column(name = "zip_code")})
@Type(type = "com.baeldung.hibernate.customtypes.AddressType")
@CompositeType(value = com.baeldung.hibernate.customtypes.AddressType.class)
@AttributeOverrides({
@AttributeOverride(name = "addressLine1", column = @Column(name = "address_line_1")),
@AttributeOverride(name = "addressLine2", column = @Column(name = "address_line_2")),
@AttributeOverride(name = "city", column = @Column(name = "city")),
@AttributeOverride(name = "country", column = @Column(name = "country")),
@AttributeOverride(name = "zipCode", column = @Column(name = "zip_code"))
})
private Address empAddress;
@Type(type = "com.baeldung.hibernate.customtypes.SalaryType",
@Type(value = com.baeldung.hibernate.customtypes.SalaryType.class,
parameters = {@Parameter(name = "currency", value = "USD")})
@Columns(columns = {@Column(name = "amount"),
@Column(name = "currency")})
@AttributeOverrides({
@AttributeOverride(name = "amount", column = @Column(name = "amount")),
@AttributeOverride(name = "currency", column = @Column(name = "currency"))
})
private Salary salary;
public Salary getSalary() {
@@ -2,11 +2,11 @@ package com.baeldung.hibernate.customtypes;
import java.util.Objects;
public final class PhoneNumber {
public class PhoneNumber {
private final int countryCode;
private final int cityCode;
private final int number;
private int countryCode;
private int cityCode;
private int number;
public PhoneNumber(int countryCode, int cityCode, int number) {
this.countryCode = countryCode;
@@ -1,6 +1,5 @@
package com.baeldung.hibernate.customtypes;
import org.hibernate.HibernateException;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.usertype.UserType;
@@ -11,11 +10,11 @@ import java.sql.SQLException;
import java.sql.Types;
import java.util.Objects;
public class PhoneNumberType implements UserType<PhoneNumber> {
public class PhoneNumberType implements UserType {
@Override
public int[] sqlTypes() {
return new int[]{Types.INTEGER, Types.INTEGER, Types.INTEGER};
public int getSqlType() {
return Types.INTEGER;
}
@Override
@@ -24,7 +23,7 @@ public class PhoneNumberType implements UserType {
}
@Override
public boolean equals(Object x, Object y) throws HibernateException {
public boolean equals(PhoneNumber x, PhoneNumber y) {
if (x == y)
return true;
if (Objects.isNull(x) || Objects.isNull(y))
@@ -34,48 +33,42 @@ public class PhoneNumberType implements UserType {
}
@Override
public int hashCode(Object x) throws HibernateException {
public int hashCode(PhoneNumber x) {
return x.hashCode();
}
@Override
public Object nullSafeGet(ResultSet rs, String[] names, SharedSessionContractImplementor session, Object owner) throws HibernateException, SQLException {
int countryCode = rs.getInt(names[0]);
public PhoneNumber nullSafeGet(ResultSet rs, int position, SharedSessionContractImplementor session, Object owner) throws SQLException {
int countryCode = rs.getInt(position);
if (rs.wasNull())
return null;
int cityCode = rs.getInt(names[1]);
int number = rs.getInt(names[2]);
PhoneNumber employeeNumber = new PhoneNumber(countryCode, cityCode, number);
int cityCode = rs.getInt(position);
int number = rs.getInt(position);
return employeeNumber;
return new PhoneNumber(countryCode, cityCode, number);
}
@Override
public void nullSafeSet(PreparedStatement st, Object value, int index, SharedSessionContractImplementor session) throws HibernateException, SQLException {
public void nullSafeSet(PreparedStatement st, PhoneNumber value, int index, SharedSessionContractImplementor session) throws SQLException {
if (Objects.isNull(value)) {
st.setNull(index, Types.INTEGER);
st.setNull(index+1, Types.INTEGER);
st.setNull(index+2, Types.INTEGER);
} else {
PhoneNumber employeeNumber = (PhoneNumber) value;
st.setInt(index,employeeNumber.getCountryCode());
st.setInt(index+1,employeeNumber.getCityCode());
st.setInt(index+2,employeeNumber.getNumber());
st.setInt(index, value.getCountryCode());
st.setInt(index+1, value.getCityCode());
st.setInt(index+2, value.getNumber());
}
}
@Override
public Object deepCopy(Object value) throws HibernateException {
public PhoneNumber deepCopy(PhoneNumber value) {
if (Objects.isNull(value))
return null;
PhoneNumber empNumber = (PhoneNumber) value;
PhoneNumber newEmpNumber = new PhoneNumber(empNumber.getCountryCode(),empNumber.getCityCode(),empNumber.getNumber());
return newEmpNumber;
return new PhoneNumber(value.getCountryCode(), value.getCityCode(), value.getNumber());
}
@Override
@@ -84,17 +77,17 @@ public class PhoneNumberType implements UserType {
}
@Override
public Serializable disassemble(Object value) throws HibernateException {
public Serializable disassemble(PhoneNumber value) {
return (Serializable) value;
}
@Override
public Object assemble(Serializable cached, Object owner) throws HibernateException {
return cached;
public PhoneNumber assemble(Serializable cached, Object owner) {
return (PhoneNumber) cached;
}
@Override
public Object replace(Object original, Object target, Object owner) throws HibernateException {
return original;
public PhoneNumber replace(PhoneNumber detached, PhoneNumber managed, Object owner) {
return detached;
}
}
@@ -1,12 +1,12 @@
package com.baeldung.hibernate.customtypes;
import org.hibernate.HibernateException;
import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.type.LongType;
import org.hibernate.type.StringType;
import org.hibernate.type.Type;
import org.hibernate.metamodel.spi.ValueAccess;
import org.hibernate.usertype.CompositeUserType;
import org.hibernate.usertype.DynamicParameterizedType;
import org.hibernate.usertype.UserType;
import java.io.Serializable;
import java.sql.PreparedStatement;
@@ -16,65 +16,47 @@ import java.sql.Types;
import java.util.Objects;
import java.util.Properties;
public class SalaryType implements CompositeUserType, DynamicParameterizedType {
public class SalaryType implements UserType<Salary>, CompositeUserType<Salary>, DynamicParameterizedType {
private String localCurrency;
@Override
public String[] getPropertyNames() {
return new String[]{"amount", "currency"};
}
@Override
public Type[] getPropertyTypes() {
return new Type[]{LongType.INSTANCE, StringType.INSTANCE};
}
@Override
public Object getPropertyValue(Object component, int property) throws HibernateException {
Salary salary = (Salary) component;
public Object getPropertyValue(Salary component, int property) throws HibernateException {
switch (property) {
case 0:
return salary.getAmount();
return component.getAmount();
case 1:
return salary.getCurrency();
return component.getCurrency();
default:
throw new IllegalArgumentException(property +
" is an invalid property index for class type " +
component.getClass().getName());
}
throw new IllegalArgumentException(property +
" is an invalid property index for class type " +
component.getClass().getName());
}
@Override
public void setPropertyValue(Object component, int property, Object value) throws HibernateException {
Salary salary = (Salary) component;
switch (property) {
case 0:
salary.setAmount((Long) value);
case 1:
salary.setCurrency((String) value);
}
throw new IllegalArgumentException(property +
" is an invalid property index for class type " +
component.getClass().getName());
}
@Override
public Class returnedClass() {
public Salary instantiate(ValueAccess values, SessionFactoryImplementor sessionFactory) {
return null;
}
@Override
public Class<?> embeddable() {
return Salary.class;
}
@Override
public boolean equals(Object x, Object y) throws HibernateException {
public int getSqlType() {
return Types.BIGINT;
}
@Override
public Class<Salary> returnedClass() {
return Salary.class;
}
@Override
public boolean equals(Salary x, Salary y) {
if (x == y)
return true;
@@ -82,54 +64,48 @@ public class SalaryType implements CompositeUserType, DynamicParameterizedType {
return false;
return x.equals(y);
}
@Override
public int hashCode(Object x) throws HibernateException {
public int hashCode(Salary x) {
return x.hashCode();
}
@Override
public Object nullSafeGet(ResultSet rs, String[] names, SharedSessionContractImplementor session, Object owner) throws HibernateException, SQLException {
public Salary nullSafeGet(ResultSet rs, int position, SharedSessionContractImplementor session, Object owner) throws SQLException {
Salary salary = new Salary();
salary.setAmount(rs.getLong(names[0]));
salary.setAmount(rs.getLong(position));
if (rs.wasNull())
return null;
salary.setCurrency(rs.getString(names[1]));
salary.setCurrency(rs.getString(position));
return salary;
}
@Override
public void nullSafeSet(PreparedStatement st, Object value, int index, SharedSessionContractImplementor session) throws HibernateException, SQLException {
public void nullSafeSet(PreparedStatement st, Salary value, int index, SharedSessionContractImplementor session) throws SQLException {
if (Objects.isNull(value))
st.setNull(index, Types.BIGINT);
else {
Salary salary = (Salary) value;
st.setLong(index, SalaryCurrencyConvertor.convert(salary.getAmount(),
salary.getCurrency(), localCurrency));
st.setString(index + 1, salary.getCurrency());
st.setLong(index, SalaryCurrencyConvertor.convert(
value.getAmount(),
value.getCurrency(), localCurrency));
st.setString(index + 1, value.getCurrency());
}
}
@Override
public Object deepCopy(Object value) throws HibernateException {
public Salary deepCopy(Salary value) {
if (Objects.isNull(value))
return null;
Salary oldSal = (Salary) value;
Salary newSal = new Salary();
newSal.setAmount(oldSal.getAmount());
newSal.setCurrency(oldSal.getCurrency());
newSal.setAmount(value.getAmount());
newSal.setCurrency(value.getCurrency());
return newSal;
}
@@ -140,18 +116,18 @@ public class SalaryType implements CompositeUserType, DynamicParameterizedType {
}
@Override
public Serializable disassemble(Object value, SharedSessionContractImplementor session) throws HibernateException {
public Serializable disassemble(Salary value) {
return (Serializable) deepCopy(value);
}
@Override
public Object assemble(Serializable cached, SharedSessionContractImplementor session, Object owner) throws HibernateException {
return deepCopy(cached);
public Salary assemble(Serializable cached, Object owner) {
return deepCopy((Salary) cached);
}
@Override
public Object replace(Object original, Object target, SharedSessionContractImplementor session, Object owner) throws HibernateException {
return original;
public Salary replace(Salary detached, Salary managed, Object owner) {
return detached;
}
@Override
@@ -4,7 +4,7 @@ import org.hibernate.annotations.Cascade;
import org.hibernate.annotations.CascadeType;
import org.hibernate.annotations.Immutable;
import javax.persistence.*;
import jakarta.persistence.*;
import java.util.Set;
@Entity
@@ -3,7 +3,7 @@ package com.baeldung.hibernate.immutable.entities;
import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.Immutable;
import javax.persistence.*;
import jakarta.persistence.*;
@Entity
@Immutable
@@ -1,12 +1,12 @@
package com.baeldung.hibernate.joincolumn;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import jakarta.persistence.Entity;
import jakarta.persistence.FetchType;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.ManyToOne;
@Entity
public class Email {
@@ -1,13 +1,13 @@
package com.baeldung.hibernate.joincolumn;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinColumns;
import javax.persistence.ManyToOne;
import jakarta.persistence.Entity;
import jakarta.persistence.FetchType;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.JoinColumns;
import jakarta.persistence.ManyToOne;
@Entity
public class Office {
@@ -1,10 +1,10 @@
package com.baeldung.hibernate.joincolumn;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
@Entity
public class OfficeAddress {
@@ -1,12 +1,12 @@
package com.baeldung.hibernate.joincolumn;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import jakarta.persistence.Entity;
import jakarta.persistence.FetchType;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.OneToMany;
@Entity
public class OfficialEmployee {
@@ -3,12 +3,12 @@ package com.baeldung.hibernate.lazycollection.model;
import org.hibernate.annotations.LazyCollection;
import org.hibernate.annotations.LazyCollectionOption;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OrderColumn;
import javax.persistence.OneToMany;
import javax.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.OrderColumn;
import jakarta.persistence.OneToMany;
import jakarta.persistence.Entity;
import java.util.ArrayList;
import java.util.List;
@@ -1,11 +1,10 @@
package com.baeldung.hibernate.lazycollection.model;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OrderColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.ManyToOne;
import jakarta.persistence.Entity;
@Entity
public class Employee {

Some files were not shown because too many files have changed in this diff Show More