Java Libraries
Copy JAR files which are listed below:
antlr-2.7.7.jar
classmate-1.3.4.jar
commons-lang3-3.6.jar
commons-logging-1.1.3.jar
dom4j-1.6.1.jar
ehcache-core-2.6.11.jar
geolatte-geom-1.1.0.jar
hibernate-commons-annotations-5.0.1.Final.jar
hibernate-core-5.2.11.Final.jar
hibernate-ehcache-5.2.12.Final.jar
hibernate-ejb3-persistence.jar
hibernate-enhance-maven-plugin-4.3.7.Final.jar
hibernate-entitymanager-5.2.12.Final.jar
hibernate-java8-5.2.11.Final.jar
hibernate-jpa-2.1-api-1.0.0.Final.jar
hibernate-spatial-5.2.11.Final.jar
hibernate-validator-6.0.2.Final.jar
javassist-3.16.1-GA.jar
jboss-logging-3.3.1.Final.jar
jboss-transaction-api_1.1_spec-1.0.1.Final.jar
jts-1.11.jar
mysql-connector-java-5.1.36.jar
slf4j-api-1.7.21.jar
classmate-1.3.0.jar
el-api-2.2.1-b04.jar
hibernate-validator-5.2.2.Final.jar
validation-api-1.1.0.Final.jar
Create Database
Create a database with the name is hibernate5. This database have a table: Account table.
--
--
-- Table structure for table `account`
--
CREATE TABLE `account` (
`id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
`username` varchar(250) NOT NULL,
`password` varchar(250) NOT NULL,
`fullName` varchar(250) NOT NULL,
`status` tinyint(1) NOT NULL,
`birthday` date NOT NULL,
`email` varchar(250) NOT NULL,
`website` varchar(250) NOT NULL,
`age` int(2) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
--
-- Dumping data for table `account`
--
INSERT INTO `account` (`username`, `password`, `fullName`, `status`, `birthday`, `email`, `website`, `age`) VALUES
('acc1', '123', 'Account 1', 1, '1980-12-05', 'a@gmail.com', 'http://abc.com', 20);
INSERT INTO `account` (`username`, `password`, `fullName`, `status`, `birthday`, `email`, `website`, `age`) VALUES
('acc2', '123', 'Account 2', 0, '1989-20-05', 'b@gmail.com', 'http://abc.com', 21);
Structure of Account Table
Account Table
Entities Class
Create a entity classes – Account.java to represent the above table and put annotations to validate values of account object
Account.java
package entities;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import static javax.persistence.GenerationType.IDENTITY;
import java.util.Date;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Past;
import javax.validation.constraints.Pattern;
import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.Length;
import org.hibernate.validator.constraints.NotEmpty;
import org.hibernate.validator.constraints.URL;
@Entity
@Table(name = "account")
public class Account implements java.io.Serializable {
private Integer id;
private String username;
private String password;
private String fullName;
private boolean status;
private Date birthday;
private String email;
private String website;
private int age;
@Id
@GeneratedValue(strategy = IDENTITY)
@Column(name = "id", unique = true, nullable = false)
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
@NotEmpty
@Length(min = 3, max = 10)
@Column(name = "username", nullable = false, length = 250)
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
@Pattern(regexp = "((?=.*\\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%]).{6,20})")
@NotEmpty
@Column(name = "password", nullable = false, length = 250)
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Column(name = "fullName", nullable = false, length = 250)
public String getFullName() {
return fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
@Column(name = "status", nullable = false)
public boolean isStatus() {
return status;
}
public void setStatus(boolean status) {
this.status = status;
}
@Past
@NotNull
@Temporal(TemporalType.DATE)
@Column(name = "birthday", nullable = false, length = 0)
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
@NotEmpty
@Email
@Column(name = "email", nullable = false, length = 250)
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@URL
@Column(name = "website", nullable = false, length = 250)
public String getWebsite() {
return website;
}
public void setWebsite(String website) {
this.website = website;
}
@NotNull
@Min(18)
@Max(120)
@Column(name = "age", nullable = false)
public int getAge() {
return this.age;
}
public void setAge(int age) {
this.age = age;
}
}
Hibernate Configuration File
Puts Account.java in your Hibernate configuration file, and also MySQL connection details.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.enable_lazy_load_no_trans">true</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.password">123456</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernate5</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.dialect">org.hibernate.spatial.dialect.mysql.MySQLSpatialDialect</property>
<property name="hibernate.current_session_context_class">thread</property>
<mapping class="entities.Account" />
</session-factory>
</hibernate-configuration>
Create HibernateUtil class
The HibernateUtil class helps in creating the SessionFactory from the Hibernate configuration file. The SessionFactory is threadsafe, so it is not necessary to obtain one for each thread.
package validator;
import org.hibernate.*;
import org.hibernate.boot.*;
import org.hibernate.boot.registry.*;
public class HibernateUtil {
private static final SessionFactory sessionFactory;
static {
try {
StandardServiceRegistry standardRegistry = new
StandardServiceRegistryBuilder()
.configure("hibernate.cfg.xml")
.build();
Metadata metaData = new MetadataSources(
standardRegistry)
.getMetadataBuilder()
.build();
sessionFactory = metaData.getSessionFactoryBuilder().build();
} catch (Throwable th) {
throw new ExceptionInInitializerError(th);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
Create AccountModel class
The AccountModel class contains methods to interact with the database.
package validator;
import org.hibernate.*;
import entities.*;
public class AccountModel {
private SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
public Boolean create(Account account) {
Boolean result = true;
Session session = null;
Transaction transaction = null;
try {
session = sessionFactory.openSession();
transaction = session.beginTransaction();
session.save(account);
transaction.commit();
} catch (Exception e) {
result = false;
if (transaction != null) {
transaction.rollback();
}
} finally {
session.close();
}
return result;
}
}
Run It
package validator;
import java.text.SimpleDateFormat;
import java.util.Set;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import entities.Account;
public class Main {
public static void main(String[] args) {
try {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
AccountModel accountModel = new AccountModel();
Account account = new Account();
account.setUsername("");
account.setPassword("123");
account.setEmail("a");
account.setWebsite("b");
account.setAge(200);
account.setBirthday(simpleDateFormat.parse("2050-10-20"));
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
Validator validator = factory.getValidator();
Set<ConstraintViolation<Account>> constraintViolations = validator.validate(account);
if (!constraintViolations.isEmpty()) {
for (ConstraintViolation<Account> constraintViolation : constraintViolations) {
System.out.println(constraintViolation.getPropertyPath() + " " + constraintViolation.getMessage());
}
} else {
accountModel.create(account);
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
Output
birthday must be in the past
website must be a valid URL
password must match "((?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%]).{6,20})"
username length must be between 3 and 10
email not a well-formed email address
username may not be empty
age must be less than or equal to 120