public class HibernateUtil {
private static final SessionFactory sessionFactory;
static {
try {
sessionFactory = new AnnotationConfiguration()
.configure()
.buildSessionFactory();
}
catch(Exception e) {
throw new ExceptionInInitializerError(e);
}
}
public static Session getCurrentSession() {
return sessionFactory.getCurrentSession();
}
}
HibernateUtil还包含了一些辅助方法,如:
public static Object query(Class clazz, Serializable id);
public static void createEntity(Object entity);
public static Object queryForObject(String hql, Object[] params);
public static List queryForList(String hql, Object[] params);
在此不再多述。
实体类User使用JPA注解,代表一个用户:
@Entity
@Table(name="T_USER")
public class User {
public static final String REGEX_USERNAME = "[a-z0-9][a-z0-9\\-]{1,18}[a-z0-9]";
public static final String REGEX_PASSWORD = "[a-f0-9]{32}";
public static final String REGEX_EMAIL = "([0-9a-zA-Z]([-.\\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\\w]*[0-9a-zA-Z]\\.)+[a-zA-Z]{2,9})";
private String username; // 用户名
private String password; // MD5口令
private boolean admin; // 是否是管理员
private String email; // 电子邮件
private int emailValidation; // 电子邮件验证码
private long createdDate; // 创建时间
private long lockDate; // 锁定时间
public User() {}
public User(String username, String password, boolean admin, long lastSignOnDate) {
this.username = username;
this.password = password;
this.admin = admin;
}
@Id
@Column(updatable=false, length=20)
@Pattern(regex=REGEX_USERNAME)
public String getUsername() { return username; }
public void setUsername(String username) { this.username = username; }
@Column(nullable=false, length=32)
@Pattern(regex=REGEX_PASSWORD)
文章来源于领测软件测试网 https://www.ltesting.net/