因为要实现用户-角色-权限管理,所以需要多对多映射实现。经过一整天的学习与调试,终于简单的实现了该功能。以下是写的测试类,以供大家理解。
1、编写Entity Bean
package com.javaeye.sunjiesh.hibernate.annotation.entity;
import java.io.Serializable;
import java.util.LinkedHashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
@Entity
@Table(name = "USER")
public class User implements Serializable {
private static final long serialVersionUID = -171549061113198199L;
private int id;
private String username;
private String password;
private Set<Role> roles = new LinkedHashSet<Role>();
public User() {
}
@Id
@Column(name = "id", nullable = false, unique = true)
@GeneratedValue(strategy = GenerationType.AUTO)
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Column(name = "username")
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
@Column(name = "password")
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@ManyToMany(cascade = { CascadeType.PERSIST, CascadeType.MERGE })
@JoinTable(name = "USER_ROLE", joinColumns = { @JoinColumn(name = "USER_ID") }, inverseJoinColumns = { @JoinColumn(name = "ROLE_ID") })
// @Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public Set<Role> getRoles() {
return roles;
}
public void setRoles(Set<Role> roles) {
this.roles = roles;
}
}
package com.javaeye.sunjiesh.hibernate.annotation.entity;
import java.io.Serializable;
import java.util.LinkedHashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
@Entity
@Table(name = "ROLE")
public class Role implements Serializable {
private static final long serialVersionUID = 3196247728974978243L;
private int id;
private String name;
private Set<User> users=new LinkedHashSet<User>();
public Role() {
}
@Id
@Column(name = "id", nullable = false, unique = true)
@GeneratedValue(strategy = GenerationType.AUTO)
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Column(name = "name")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@ManyToMany(cascade = {CascadeType.PERSIST, CascadeType.MERGE }, fetch = FetchType.LAZY, mappedBy="roles")
public Set<User> getUsers() {
return users;
}
public void setUsers(Set<User> users) {
this.users = users;
}
}
2、编写Hibernate配置文件
<?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 name="foo"> <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property> <property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property> <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/test</property> <property name="hibernate.connection.username">*</property> <property name="hibernate.connection.password">*</property> <property name="hibernate.transaction.factory_class">org.hibernate.transaction.JDBCTransactionFactory</property> <property name="show_sql">true</property> <mapping class="com.javaeye.sunjiesh.hibernate.annotation.entity.User"/> <mapping class="com.javaeye.sunjiesh.hibernate.annotation.entity.Role"/> </session-factory> </hibernate-configuration>
3、编写HibernateSessionFactory类(与MyEclipse自动生成的有少量变动)
package com.javaeye.sunjiesh.util;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.cfg.Configuration;
/**
* Configures and provides access to Hibernate sessions, tied to the
* current thread of execution. Follows the Thread Local Session
* pattern, see {@link http://hibernate.org/42.html }.
*/
public class HibernateSessionFactory {
/**
* Location of mysqlhibernate.cfg.xml file.
* Location should be on the classpath as Hibernate uses
* #resourceAsStream style lookup for its configuration file.
* The default classpath location of the hibernate config file is
* in the default package. Use #setConfigFile() to update
* the location of the configuration file for the current session.
*/
private static String CONFIG_FILE_LOCATION = "mysqlhibernate.cfg.xml";
private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
//private static Configuration configuration = new Configuration();
private static AnnotationConfiguration configuration=new AnnotationConfiguration();
private static org.hibernate.SessionFactory sessionFactory;
private static String configFile = CONFIG_FILE_LOCATION;
static {
try {
configuration.configure(configFile);
sessionFactory = configuration.buildSessionFactory();
} catch (Exception e) {
System.err
.println("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
}
}
private HibernateSessionFactory() {
}
/**
* Returns the ThreadLocal Session instance. Lazy initialize
* the <code>SessionFactory</code> if needed.
*
* @return Session
* @throws HibernateException
*/
public static synchronized Session getSession() throws HibernateException {
Session session = (Session) threadLocal.get();
if (session == null || !session.isOpen()) {
if (sessionFactory == null) {
rebuildSessionFactory();
}
session = (sessionFactory != null) ? sessionFactory.openSession()
: null;
threadLocal.set(session);
}
return session;
}
/**
* Rebuild hibernate session factory
*
*/
public static void rebuildSessionFactory() {
try {
configuration.configure(configFile);
sessionFactory = configuration.buildSessionFactory();
} catch (Exception e) {
System.err
.println("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
}
}
/**
* Close the single hibernate session instance.
*
* @throws HibernateException
*/
public static void closeSession() throws HibernateException {
Session session = (Session) threadLocal.get();
threadLocal.set(null);
if (session != null) {
session.close();
}
}
/**
* return session factory
*
*/
public static org.hibernate.SessionFactory getSessionFactory() {
return sessionFactory;
}
/**
* return session factory
*
* session factory will be rebuilded in the next call
*/
public static void setConfigFile(String configFile) {
HibernateSessionFactory.configFile = configFile;
sessionFactory = null;
}
/**
* return hibernate configuration
*
*/
public static Configuration getConfiguration() {
return configuration;
}
}
4、编写DAO类
package com.javaeye.sunjiesh.dao;
import java.io.Serializable;
import org.apache.log4j.Logger;
import org.hibernate.Session;
import org.hibernate.Transaction;
import com.javaeye.sunjiesh.util.HibernateSessionFactory;
public abstract class BaseDAO<T> {
private static Logger log =Logger.getLogger(BaseDAO.class);
/**
* 获取Hibernate的Session对象
*/
public Session getSession(){
return HibernateSessionFactory.getSession();
}
/**
* 根据主键得到对象
*/
public T getObject(Class clazz, Serializable id){
return (T)getSession().get(clazz, id);
}
/**
* 保存对象
*/
public void saveObject(T t) {
Session session = getSession();
Transaction tx = beginTransaction(session);
try{
session.saveOrUpdate(t);
tx.commit();
}catch(Exception e){
tx.rollback();
log.error("保存对象失败");
}
}
/**
* 创建事务
*/
private Transaction beginTransaction(Session session){
return session.beginTransaction();
}
}
package com.javaeye.sunjiesh.dao;
import com.javaeye.sunjiesh.hibernate.annotation.entity.Role;
public class RoleDAO extends BaseDAO<Role> {
}
package com.javaeye.sunjiesh.dao;
import com.javaeye.sunjiesh.hibernate.annotation.entity.User;
public class UserDAO extends BaseDAO<User>{
}
5、编写测试类
package com.javaeye.sunjiesh.hibernate.annotation;
import com.javaeye.sunjiesh.dao.RoleDAO;
import com.javaeye.sunjiesh.dao.UserDAO;
import com.javaeye.sunjiesh.hibernate.annotation.entity.Role;
import com.javaeye.sunjiesh.hibernate.annotation.entity.User;
public class AnnotationMain {
public AnnotationMain() {
// TODO Auto-generated constructor stub
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
User user=new User();
user.setUsername("username");
user.setPassword("password");
Role role=new Role();
role.setName("管理员");
UserDAO userDao=new UserDAO();
RoleDAO roleDao=new RoleDAO();
userDao.saveObject(user);
roleDao.saveObject(role);
user.getRoles().add(role);
role.getUsers().add(user);
userDao.saveObject(user);
roleDao.saveObject(role);
}
}
备注:此篇文章为双向多对多关系。