MyException - 我的异常网
当前位置:我的异常网» 软件架构设计 » SSH框架调整入门helloworld两种事务管理方式(失败的

SSH框架调整入门helloworld两种事务管理方式(失败的自己)

www.MyException.Cn  网友分享于:2015-08-26  浏览:24次
SSH框架整合入门helloworld两种事务管理方式(失败的自己)

 

 

这里的hibernate功能没有真正的使用

 

首先当然是jar包了:

 

struts2里面的Jar包:下载的struts2压缩包里面的struts-2.3.15.1\apps\struts2-blank,直接引入,另外就是struts2-spring-plugin-2.3.15.1.jar这个struts2和spring整合的jar

 

hibernate:  hibernate3.jar是肯定的,另外就是hibernate-distribution-3.6.10.Final\lib\required下面的必须的包,以及jpa下面的hibernate-jpa-2.0-api-1.0.1.Final.jar

 

spring:  spring.jar

   

cglib-nodep-2.1_3.jar

 

slf4j-api-1.5.0.jar

 

slf4j-log4j12-1.5.0.jar

 

还有就是连接数据库的(mysql为例:)mysql-connector-java-5.0.8-bin.jar

 

所有的包在图片里面有汇总

 

 

好了,下面开始进入正题:

 

web.xml:

 

 

<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_9" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

	<display-name>Struts Blank</display-name>
	<!-- 指定spring配置文件applicationContext.xml(可以多个)的位置 -->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath*:applicationContext.xml</param-value>
	</context-param>
	<!-- 服务器启动的时候加载spring -->
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
	<!-- 配置struts2的filter -->
	<filter>
		<filter-name>struts2</filter-name>
		<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
	</filter>
	<filter-mapping>
		<filter-name>struts2</filter-name>
		<url-pattern>*.action</url-pattern>
	</filter-mapping>
	<!-- 配置字符编码过滤器 -->
	<filter>
		<filter-name>encodingFilter</filter-name>
		<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
		<init-param>
			<param-name>encoding</param-name>
			<param-value>utf-8</param-value>
		</init-param>
	</filter>
	<filter-mapping>
		<filter-name>encodingFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
	<welcome-file-list>
		<welcome-file>index.jsp</welcome-file>
	</welcome-file-list>

</web-app>

 

 

 

applicationContext.xml:注解事务管理,需要在方法上加@Transactional(propagation=Propagation.REQUIRED,rollbackFor=Exception.class)

 

<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
				http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
				http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
	<!-- 启动注入功能 -->
	<context:annotation-config />
	<!-- 启动扫描component功能 -->
	<context:component-scan base-package="com.tch.test" />
	<!-- 启动注解实物配置功能 -->
	<tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true"/>
	<!-- 数据源 -->
	<bean id="dataSource"
		class="org.springframework.jdbc.datasource.DriverManagerDataSource">
		<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
		<property name="url" value="jdbc:mysql://localhost:3306/test"></property>
		<property name="username" value="root"></property>
		<property name="password" value="root"></property>
	</bean>
	<!-- 事务管理器 -->
	<bean id="transactionManager"
		class="org.springframework.orm.hibernate3.HibernateTransactionManager">
		<property name="sessionFactory" ref="sessionFactory" />
	</bean>
	<!--读取数据库配置文件  -->
	<bean id="sessionFactory"
		class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
		<property name="dataSource" ref="dataSource"/>
		<property name="mappingLocations">
			 <value>classpath:com/tch/test/ssh/entity/*.hbm.xml</value>
		</property>
		<property name="hibernateProperties">
			<props>
				<prop key="hibernate.show_sql">true</prop>
			</props>
		</property>
	</bean>
</beans>

 

xml文件配置的事务管理方式:这种方式不需要在方法上加@Transactional(propagation=Propagation.REQUIRED,rollbackFor=Exception.class)

 

<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
	xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
				http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
				http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
				http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
	<!-- 启动注入功能 -->
	<context:annotation-config />
	<!-- 启动扫描component功能 -->
	<context:component-scan base-package="test,com.tch.test" />
	<!-- 不启动注解实物配置功能 
	<tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true"/>
	-->
	<tx:advice id="txAdvice" transaction-manager="transactionManager">
		<tx:attributes>
			<tx:method name="get*" read-only="true"/>
			<tx:method name="select*" read-only="true"/>
			<tx:method name="*" propagation="REQUIRED" rollback-for="java.lang.Exception"/>
		</tx:attributes>
	</tx:advice>
	<aop:config>
		<aop:pointcut expression="execution(* com.tch.test.ssh..*.*(..))" id="testpointcut"/>
		<aop:advisor advice-ref="txAdvice" pointcut-ref="testpointcut"/>
	</aop:config>
	<!-- 数据源 -->
	<bean id="dataSource"
		class="org.springframework.jdbc.datasource.DriverManagerDataSource">
		<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
		<property name="url" value="jdbc:mysql://localhost:3306/test"></property>
		<property name="username" value="root"></property>
		<property name="password" value="root"></property>
	</bean>
	<!-- 事务管理器 -->
	<bean id="transactionManager"
		class="org.springframework.orm.hibernate3.HibernateTransactionManager">
		<property name="sessionFactory" ref="sessionFactory" />
	</bean>
	<!--读取数据库配置文件  -->
	<bean id="sessionFactory"
		class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
		<property name="dataSource" ref="dataSource"/>
		<property name="mappingLocations">
			 <value>classpath:com/tch/test/ssh/entity/*.hbm.xml</value>
		</property>
		<property name="hibernateProperties">
			<props>
				<prop key="hibernate.show_sql">true</prop>
			</props>
		</property>
	</bean>
</beans>

 

 

 

 

struts.xml:

 

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
	"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
	"http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
	<constant name="struts.enable.DynamicMethodInvocation" value="true" />
	<constant name="struts.devMode" value="true" />
	<package name="default" namespace="/" extends="struts-default">
		<default-action-ref name="index" />
		<global-results>
			<result name="error">/error.jsp</result>
		</global-results>
		<global-exception-mappings>
			<exception-mapping exception="java.lang.Exception"
				result="error" />
		</global-exception-mappings>
		<action name="show" class="userAction" method="select">
			<result>/WEB-INF/pages/User.jsp</result>
		</action>
		<action name="goEdit" class="userAction" method="goEdit">
			<result>/WEB-INF/pages/editUser.jsp</result>
		</action>
		<!-- 使用通配符 -->
		<action name="*User" class="userAction" method="{1}User">
			<result type="redirectAction">
				<param name="actionName">show</param>
				<param name="namespace">/</param>
			</result>
		</action>
	</package>
</struts>

 

 

 

action:

 

 

package com.tch.test.ssh.web.action;

import java.util.List;
import java.util.Set;

import javax.annotation.Resource;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.opensymphony.xwork2.ActionSupport;
import com.tch.test.ssh.entity.Priority;
import com.tch.test.ssh.entity.User;
import com.tch.test.ssh.service.IPriorityService;
import com.tch.test.ssh.service.IUserService;

@Component("userAction")
@Scope("prototype")
public class UserAction extends ActionSupport {
	private static final long serialVersionUID = 1L;
	
	private User user;
	private List<Priority> priorities;
	
	@Resource(name="userService")
	private IUserService userService;
	@Resource(name="priorityService")
	private IPriorityService priorityService;
	
	private List<User> users;
	private List<String> priorityName;

	public List<String> getPriorityName() {
		return priorityName;
	}

	public void setPriorityName(List<String> priorityName) {
		this.priorityName = priorityName;
	}

	public String select() throws Exception{
		users = userService.select();
		System.out.println("所有用户数:"+users.size());
		return "success";
	}
	
	public String addUser() throws Exception{
		System.out.println("add ..  "+user);
		userService.add(user);
		return "success";
	}
	public String goEdit() throws Exception{
		user = userService.getUserById(user.getId());
		priorities = priorityService.getPriorityByUserId(user.getId());
		System.out.println(user);
		return "success";
	}
	/**
	 * 删除用户
	 * @return
	 * @throws Exception
	 */
	public String deleteUser() throws Exception{
		userService.deleteUser(user.getId());
		return "success";
	}
	/**
	 * 修改用户信息
	 * @return
	 * @throws Exception
	 */
	public String editUser() throws Exception{
		try {
			Set<Priority> priorities = priorityService.getPrioritiesByNames(priorityName);
			user.setPriorities(priorities);
			userService.editUser(user);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "success";
	}

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}


	public List<Priority> getPriorities() {
		return priorities;
	}

	public void setPriorities(List<Priority> priorities) {
		this.priorities = priorities;
	}

	public List<User> getUsers() {
		return users;
	}

	public void setUsers(List<User> users) {
		this.users = users;
	}
	
}

 service接口:

 

package com.tch.test.ssh.service;

import java.util.List;
import java.util.Set;

import com.tch.test.ssh.entity.Priority;

public interface IPriorityService {

	/**
	 * 根据id获取user对象
	 * @param id
	 * @return
	 */
	List<Priority> getPriorityByUserId(Integer id) throws Exception;
	/**
	 * 根据id获取实体对象
	 * @param id
	 * @return
	 */
	Priority getEntity(Integer id) throws Exception;
	/**
	 * 根据name获取实体对象
	 * @param id
	 * @return
	 */
	Set<Priority> getPrioritiesByNames(List<String> names) throws Exception;
	/**
	 * 测试事务
	 * @throws Exception
	 */
	void testTransaction() throws Exception;
}
 

 

 

 

package com.tch.test.ssh.service;

import java.util.List;

import com.tch.test.ssh.entity.User;

public interface IUserService {
	/**
	 * 测试事务特性
	 */
	void testTransaction() throws Exception;
	/**
	 * 添加user对象
	 * @param id
	 * @return
	 */
	void add(User user) throws Exception;
	/**
	 * 查询所有user对象
	 * @param id
	 * @return
	 */
	List<User> select() throws Exception;
	/**
	 * 根据id获取user对象
	 * @param id
	 * @return
	 */
	User getUserById(Integer id) throws Exception;

	/**
	 * 根据id获取user对象
	 * @param id
	 * @return
	 */
	void editUser(User user) throws Exception;
	/**
	 * 根据id获取实体对象
	 * @param id
	 * @return
	 */
	User getEntity(Integer id) throws Exception;
	/**
	 * 删除用户
	 * @param id
	 */
	void deleteUser(Integer id) throws Exception;
}
 

 

service实现类:

 

package com.tch.test.ssh.service;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.tch.test.ssh.dao.IPriorityDao;
import com.tch.test.ssh.entity.Priority;

@Service("priorityService")
public class PriorityServiceImpl implements IPriorityService {

	@Resource(name="priorityDao")
	private IPriorityDao priorityDao;

	@Override
	@Transactional(propagation=Propagation.REQUIRED,rollbackFor=Exception.class)
	public List<Priority> getPriorityByUserId(Integer id) throws Exception{
		return priorityDao.getPriorityByUserId(id);
	}

	@Override
	@Transactional(propagation=Propagation.REQUIRED,rollbackFor=Exception.class)
	public Priority getEntity(Integer id) throws Exception {
		return priorityDao.getEntity(id);
	}

	@Override
	@Transactional(propagation=Propagation.REQUIRED,rollbackFor=Exception.class)
	public void testTransaction() throws Exception {
		Priority p = new Priority();
		p.setName("测试");
		priorityDao.add(p);
		boolean b=true;
		if(b){
			throw new Exception("priority 抛出异常。。。。");
		}
	}

	@Override
	public Set<Priority> getPrioritiesByNames(List<String> names) throws Exception {
		Set<Priority> priorities = new HashSet<Priority>();
		if(names == null || names.size() <= 0){
			return null;
		}
		Priority p = null;
		for(String name:names){
			p = priorityDao.getPriorityByName(name);
			priorities.add(p);
		}
		return priorities;
	}
	
	

}
 

 

 

package com.tch.test.ssh.service;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.tch.test.ssh.dao.IUserDao;
import com.tch.test.ssh.entity.User;

@Service("userService")
@Transactional(propagation=Propagation.REQUIRED)
public class UserServiceImpl implements IUserService {

	@Resource(name="userDao")
	private IUserDao userDao;
	
	@Override
	@Transactional(propagation=Propagation.REQUIRED,rollbackFor=Exception.class)
	public void add(User user) throws Exception {
		userDao.add(user);
	}

	@Override
	@Transactional(propagation=Propagation.REQUIRED,rollbackFor=Exception.class)
	public void editUser(User user)  throws Exception{
		userDao.editUser(user);
	}

	@Override
	@Transactional(propagation=Propagation.REQUIRED,rollbackFor=Exception.class)
	public User getUserById(Integer id) throws Exception {
		return userDao.getUserById(id);
	}

	@Override
	@Transactional(propagation=Propagation.REQUIRED,rollbackFor=Exception.class)
	public List<User> select() throws Exception {
		return userDao.select();
	}

	@Override
	@Transactional(propagation=Propagation.REQUIRED,rollbackFor=Exception.class)
	public User getEntity(Integer id) throws Exception {
		return userDao.getEntity(id);
	}

	@Override
	@Transactional(propagation=Propagation.REQUIRED,rollbackFor=Exception.class)
	public void testTransaction() throws Exception {
		User user = new User();
		user.setName("test");
		user.setPassword("password");
		userDao.add(user);
		boolean b=true;
		if(b){
			throw new Exception("priority 抛出异常。。。。");
		}
	}

	@Override
	@Transactional(propagation=Propagation.REQUIRED,rollbackFor=Exception.class)
	public void deleteUser(Integer id) throws Exception {
		userDao.delete(userDao.getEntity(id));		
	}

}
 

 

 

 

dao:

 

package com.tch.test.ssh.dao;

import javax.annotation.Resource;

import org.hibernate.SessionFactory;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

public class CommomDao extends HibernateDaoSupport{

	@Resource(name="sessionFactory")
	public void setSuperSessionFactory(SessionFactory sessionFactory){
		this.setSessionFactory(sessionFactory);
	}
	
}

 

package com.tch.test.ssh.dao;

import java.util.List;

import com.tch.test.ssh.entity.Priority;

public interface IPriorityDao {
	/**
	 * 根据id获取user对象
	 * @param id
	 * @return
	 */
	List<Priority> getPriorityByUserId(Integer id) throws Exception;
	/**
	 * 添加user对象
	 * @param id
	 * @return
	 */
	void add(Priority user) throws Exception;
	/**
	 * 根据id获取实体对象
	 * @param id
	 * @return
	 */
	Priority getEntity(Integer id) throws Exception;
	/**
	 * 删除对象
	 * @param user
	 * @throws Exception
	 */
	void delete(Priority user) throws Exception;
	/**
	 * 更新对象
	 * @param user
	 * @throws Exception
	 */
	void update(Priority user) throws Exception;
	/**
	 * 根据name获取实体对象
	 * @param id
	 * @return
	 */
	Priority getPriorityByName(String name) throws Exception;
}

 

package com.tch.test.ssh.dao;

import java.util.List;

import com.tch.test.ssh.entity.User;

public interface IUserDao {

	/**
	 * 添加user对象
	 * @param id
	 * @return
	 */
	void add(User user) throws Exception;
	/**
	 * 查询所有user对象
	 * @param id
	 * @return
	 */
	List<User> select() throws Exception;
	/**
	 * 根据id获取user对象
	 * @param id
	 * @return
	 */
	User getUserById(Integer id) throws Exception;

	/**
	 * 根据id获取user对象
	 * @param id
	 * @return
	 */
	void editUser(User user) throws Exception;
	
	/**
	 * 根据id获取实体对象
	 * @param id
	 * @return
	 */
	User getEntity(Integer id) throws Exception;
	/**
	 * 删除对象
	 * @param user
	 * @throws Exception
	 */
	void delete(User user) throws Exception;
	/**
	 * 更新对象
	 * @param user
	 * @throws Exception
	 */
	void update(User user) throws Exception;
	/**
	 * 测试事务
	 */
	void testTransaction() throws Exception;
}

 

 

 

package com.tch.test.ssh.dao;

import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Repository;

import com.tch.test.ssh.entity.Priority;

@Repository("priorityDao")
public class PriorityDaoImpl extends CommomDao implements IPriorityDao {

	/**
	 * 根据用户id查询用户权限
	 * @param id
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@Override
	public List<Priority> getPriorityByUserId(Integer id) throws Exception {
		List<Priority> priorities = new ArrayList<Priority>();
		String sql = " select p.id,p.name from User u , Priority p , User_Priority up where u.id = :id and u.id = up.userId and p.id = up.priorityId ";
		List<Object[]> result = getSessionFactory().getCurrentSession().createSQLQuery(sql).setInteger("id", id).list();
		if(result != null && result.size()>0){
			Priority temp = null;
			for(Object[] obj:result){
				temp = new Priority();
				temp.setId(Integer.parseInt(obj[0].toString()));
				temp.setName(obj[1].toString());
				priorities.add(temp);
			}
		}
		return priorities;
	}

	@Override
	public Priority getEntity(Integer id) throws Exception {
		return (Priority) getHibernateTemplate().get(Priority.class, id);
	}

	@Override
	public void delete(Priority user) throws Exception {
		getHibernateTemplate().delete(user);
	}

	@Override
	public void update(Priority user) throws Exception {
		getHibernateTemplate().update(user);
	}

	@Override
	public void add(Priority user) throws Exception {
		getHibernateTemplate().save(user);
	}

	@Override
	public Priority getPriorityByName(String name) throws Exception {
		return (Priority) getSession().createQuery(" from Priority where name = :name").setString("name", name).uniqueResult();
	}

}

 

package com.tch.test.ssh.dao;

import java.util.List;

import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.tch.test.ssh.entity.User;

@Repository("userDao")
public class UserDaoImpl extends CommomDao implements IUserDao{
	
	@Override
	public void add(User user) throws Exception{
		getSession().save(user);
	}
	@SuppressWarnings("unchecked")
	@Override
	public List<User> select() throws Exception{
		return getSessionFactory().openSession().createQuery(" from User").list();
	}

	
	
	/**
	 * 根据id获取user对象
	 * @param id
	 * @return
	 */
	@Override
	public User getUserById(Integer id) throws Exception {
		System.out.println("id: "+id);
		return (User) getSession().createQuery(" from User where id = "+id).uniqueResult();
	}
	
	/**
	 * 修改用户权限
	 * @param id
	 * @param priorities
	 */
	@Override
	public void editUser(User user)  throws Exception{
		getHibernateTemplate().saveOrUpdate(user);
	}
	@Override
	public User getEntity(Integer id) throws Exception {
		return (User) getHibernateTemplate().get(User.class, id);
	}
	@Override
	public void delete(User user) throws Exception {
		getHibernateTemplate().delete(user);		
	}
	@Override
	public void update(User user) throws Exception {
		getHibernateTemplate().update(user);		
	}
	@Override
	@Transactional(propagation=Propagation.REQUIRED,rollbackFor=Exception.class)
	public void testTransaction() throws Exception {
		User user = new User();
		user.setName("test");
		user.setPassword("password");
		add(user);
		boolean b=true;
		if(b){
			throw new Exception("priority 抛出异常。。。。");
		}
	}

}

 

 

 

 

 

实体类:Priority.java 

 

 

package com.tch.test.ssh.entity;

import java.util.Set;

/**
 * Priority entity. @author MyEclipse Persistence Tools
 */

public class Priority implements java.io.Serializable {

	// Fields
	private static final long serialVersionUID = 1L;
	private Integer id;
	private String name;
	private Set<User> users;

	// Constructors

	/** default constructor */
	public Priority() {
	}

	@Override
	public String toString() {
		return "Priority [id=" + id + ", name=" + name + "]";
	}

	/** full constructor */
	public Priority(String name) {
		this.name = name;
	}

	// Property accessors

	public Integer getId() {
		return this.id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public String getName() {
		return this.name;
	}

	public Set<User> getUsers() {
		return users;
	}

	public void setUsers(Set<User> users) {
		this.users = users;
	}

	public void setName(String name) {
		this.name = name;
	}

}

 

 

 User.java 

 

package com.tch.test.ssh.entity;

import java.util.Set;

/**
 * User entity. @author MyEclipse Persistence Tools
 */

public class User implements java.io.Serializable {

	// Fields


	private static final long serialVersionUID = 1L;
	private Integer id;
	private String name;
	private String password;
	private Set<Priority> priorities;

	// Constructors

	@Override
	public String toString() {
		return "User [id=" + id + ", name=" + name + ", password=" + password
				+ ", priorities=" + priorities + "]";
	}

	/** default constructor */
	public User() {
	}

	/** full constructor */
	public User(String name, String password) {
		this.name = name;
		this.password = password;
	}

	// Property accessors

	public Integer getId() {
		return this.id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public String getName() {
		return this.name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public Set<Priority> getPriorities() {
		return priorities;
	}

	public void setPriorities(Set<Priority> priorities) {
		this.priorities = priorities;
	}

	public String getPassword() {
		return this.password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

}

 映射文件:(没有配置表关联关系):

 User.hbm.xml

 

 

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- 
    Mapping file autogenerated by MyEclipse Persistence Tools
-->
<hibernate-mapping>
    <class name="com.tch.test.ssh.entity.User" table="user" catalog="test">
        <id name="id" type="java.lang.Integer">
            <column name="id" />
            <generator class="identity" />
        </id>
        <property name="name" type="java.lang.String">
            <column name="name" length="20">
                <comment>姓名</comment>
            </column>
        </property>
        <property name="password" type="java.lang.String">
            <column name="password" length="20">
                <comment>密码</comment>
            </column>
        </property>
        <set name="priorities" table="User_Priority" inverse="false">
            <key column="userId"></key>
            <many-to-many class="com.tch.test.ssh.entity.Priority"
                column="priorityId"></many-to-many>
        </set>
    </class>
</hibernate-mapping>

 

 Priority.hbm.xml

 

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- 
    Mapping file autogenerated by MyEclipse Persistence Tools
-->
<hibernate-mapping>
    <class name="com.tch.test.ssh.entity.Priority" table="priority" catalog="test">
        <id name="id" type="java.lang.Integer">
            <column name="id" />
            <generator class="identity" />
        </id>
        <property name="name" type="java.lang.String">
            <column name="name" length="20">
                <comment>模块名</comment>
            </column>
        </property>
        <set name="users" table="User_Priority" inverse="true">
            <key column="priorityId"></key>
            <many-to-many class="com.tch.test.ssh.entity.User"
                column="userId"></many-to-many>
        </set>
    </class>
</hibernate-mapping>

 

 

 

页面:User.jsp

 

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib uri="/struts-tags"  prefix="s"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    <title>My JSP 'User.jsp' starting page</title>
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<style type="text/css">
		*{
			margin:0;
			padding:0;
			color:#666;
		}
		body{
			background-color: #fff;
		}
		table{
			margin:20px auto;
		}
		a{
			text-decoration: none;
			color:red;
		}
		tr{
			height:35px;
			cursor:pointer;
		}
		#_table2{
			margin-top: 20px;
		}
		.detail ._mouseover{
			background-color:#eee;
		}
		input[type='text'],input[type='password']{
			height:30px;
			border:1px solid black;
			background-color: #fff;
		}
		._eventr{
			background-color:#eee;
		}
	</style>
	<script type="text/javascript" src="<%=request.getContextPath()%>/common/js/jquery.min.js"></script>
	<script type="text/javascript">
		$(function(){
			$("tbody tr").hover(function(){
				$(this).addClass('_mouseover');
			},function(){
				$(this).removeClass('_mouseover');
			});
		});
		//添加用户
		function addUser(){
			var f = document.forms[0];
			f.action = "addUser.action";
			f.submit();
		}
		function deleteUser(id,name){
			var result = confirm("确认删除"+name+"?");
			if(result){
				window.location.href='deleteUser.action?user.id='+id;
			}
		}
	</script>
  </head>
  <body>
    
    <form action="" method="post">
    	<table cellpadding="0" cellspacing="0" border="1" width="60%" align="center" class="detail">
    		<thead>
    			<tr>
    				<th width="15%" align="center">id</th>
    				<th width="15%" align="center">用户名</th>
    				<th width="15%" align="center">密码</th>
    				<th width="15%" align="center">操作</th>
    			</tr>
    		</thead>
    		<tbody>
    			<s:iterator value="users" status="user">
	    			<tr <s:if test="#user.even">class='_eventr'</s:if>>
		   				<td width="15%" align="center"><s:property value="id"/></td>
		   				<td width="15%" align="center"><s:property value="name"/></td>
		   				<td width="15%" align="center"><s:property value="password"/></td>
		   				<td width="15%" align="center">
		   					<a href="javascript:window.location.href='goEdit.action?user.id=<s:property value='id'/>'">编辑</a>
		   					<a href="javascript:deleteUser(<s:property value='id'/>,'<s:property value='name'/>')">删除</a>
		   				</td>
		   			</tr>
	    		</s:iterator>
    		</tbody>
    	</table>
    	<table cellpadding="0" cellspacing="0" border="0" width="60%" align="center" id="_table2">
    		<tr>
    			<td colspan="3">用户名:<input type="text" name="user.name">密码:<input type="text" name="user.password"></td>
    			<td><input type="button" onclick="addUser()" value="添加用户"></td>
    		</tr>
    	</table>
    </form>
    
    
  </body>
</html>

 

 

editUser.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib uri="/struts-tags"  prefix="s"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    <title>My JSP 'User.jsp' starting page</title>
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<style type="text/css">
		*{
			margin:0;
			padding:0;
			color:#666;
			line-height:30px;
		}
		#content{
			width:500px;
			margin:30px auto;
			
		}
		input[type='checkbox']{
			margin-top: 2px;
			margin-left: 10px;
			margin-right: 10px;
		}
		input[type='text'],input[type='password']{
			height:30px;
			border:1px solid black;
			background-color: #fff;
		}
		form .priority{
			float:left
			margin-left: 20px;
		}
	</style>
  </head>
  <body>
    <div id="content">
    <form action="editUser.action" method="post" name="myform">
    	用户名:<input type="text" value="<s:property value='user.name'/>" name="user.name">
    	密码:<input type="text" value="<s:property value='user.password'/>" name="user.password"><br/>
    	<span class="priority">权限:</span><br/>
    	<input type="checkbox" name="priorityName" value="管理员" <s:if test="'管理员' in priorities.{name}">checked='checked'</s:if>>管理员<br/>
    	<input type="checkbox" name="priorityName" value="程序员"<s:if test="'程序员' in priorities.{name}">checked='checked'</s:if>>程序员<br/>
    	<input type="checkbox" name="priorityName" value="测试员"<s:if test="'测试员' in priorities.{name}">checked='checked'</s:if>>测试员<br/>
    	<input type="checkbox" name="priorityName" value="运维人员"<s:if test="'运维人员' in priorities.{name}">checked='checked'</s:if>>运维人员<br/>
    	<input type="hidden" name="user.id" value="${user.id}">
    	<input type="submit"  value="确认修改">
    </form>
    </div>
  </body>
</html>

 

 

log4j.properties:

 

#
# Log4J Settings for log4j 1.2.x (via jakarta-commons-logging)
#
# The five logging levels used by Log are (in order):
#
#   1. DEBUG (the least serious)
#   2. INFO
#   3. WARN
#   4. ERROR
#   5. FATAL (the most serious)


# Set root logger level to WARN and append to stdout
log4j.rootLogger=info, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout

# Pattern to output the caller's file name and line number.
log4j.appender.stdout.layout.ConversionPattern=%d %5p (%c:%L) - %m%n

# Print only messages of level ERROR or above in the package noModule.
log4j.logger.noModule=FATAL

log4j.logger.com.opensymphony.xwork2=info
log4j.logger.org.apache.struts2=info

 

 

测试类:

 

package com.tch.test.ssh.test;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.tch.test.ssh.entity.Priority;
import com.tch.test.ssh.entity.User;

public class SpringTest {
	
	@Test
	public void testHibernate(){
		ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
		SessionFactory sessionFactory = (SessionFactory)context.getBean("sessionFactory");
		Session session = sessionFactory.openSession();
		session.beginTransaction();
		User u = new User();
		u.setId(1);
		u = (User)session.get(User.class, 1);
		System.out.println(u.getPriorities());
		Priority p = (Priority) session.load(Priority.class, 3);
		u.getPriorities().add(p);
//		u.getPriorities().remove(p);
//		Priority p = new Priority();
//		p.setId(3);
//		u.setPriorities(null);
		
		session.update(u);
		System.out.println(u.getPriorities());
		session.getTransaction().commit();
		session.close();
	}

}

 

 

 

 

 

完整代码:网盘下载

文章评论

Java程序员必看电影
Java程序员必看电影
Web开发人员为什么越来越懒了?
Web开发人员为什么越来越懒了?
“肮脏的”IT工作排行榜
“肮脏的”IT工作排行榜
“懒”出效率是程序员的美德
“懒”出效率是程序员的美德
60个开发者不容错过的免费资源库
60个开发者不容错过的免费资源库
每天工作4小时的程序员
每天工作4小时的程序员
程序员的鄙视链
程序员的鄙视链
要嫁就嫁程序猿—钱多话少死的早
要嫁就嫁程序猿—钱多话少死的早
漫画:程序员的工作
漫画:程序员的工作
如何区分一个程序员是“老手“还是“新手“?
如何区分一个程序员是“老手“还是“新手“?
2013年美国开发者薪资调查报告
2013年美国开发者薪资调查报告
我是如何打败拖延症的
我是如何打败拖延症的
聊聊HTTPS和SSL/TLS协议
聊聊HTTPS和SSL/TLS协议
为啥Android手机总会越用越慢?
为啥Android手机总会越用越慢?
5款最佳正则表达式编辑调试器
5款最佳正则表达式编辑调试器
鲜为人知的编程真相
鲜为人知的编程真相
10个帮程序员减压放松的网站
10个帮程序员减压放松的网站
初级 vs 高级开发者 哪个性价比更高?
初级 vs 高级开发者 哪个性价比更高?
如何成为一名黑客
如何成为一名黑客
老美怎么看待阿里赴美上市
老美怎么看待阿里赴美上市
那些争议最大的编程观点
那些争议最大的编程观点
程序员的一天:一寸光阴一寸金
程序员的一天:一寸光阴一寸金
不懂技术不要对懂技术的人说这很容易实现
不懂技术不要对懂技术的人说这很容易实现
科技史上最臭名昭著的13大罪犯
科技史上最臭名昭著的13大罪犯
程序员周末都喜欢做什么?
程序员周末都喜欢做什么?
写给自己也写给你 自己到底该何去何从
写给自己也写给你 自己到底该何去何从
什么才是优秀的用户界面设计
什么才是优秀的用户界面设计
当下全球最炙手可热的八位少年创业者
当下全球最炙手可热的八位少年创业者
程序员最害怕的5件事 你中招了吗?
程序员最害怕的5件事 你中招了吗?
为什么程序员都是夜猫子
为什么程序员都是夜猫子
我的丈夫是个程序员
我的丈夫是个程序员
中美印日四国程序员比较
中美印日四国程序员比较
10个调试和排错的小建议
10个调试和排错的小建议
程序员和编码员之间的区别
程序员和编码员之间的区别
程序猿的崛起——Growth Hacker
程序猿的崛起——Growth Hacker
代码女神横空出世
代码女神横空出世
老程序员的下场
老程序员的下场
程序员都该阅读的书
程序员都该阅读的书
亲爱的项目经理,我恨你
亲爱的项目经理,我恨你
程序员应该关注的一些事儿
程序员应该关注的一些事儿
Web开发者需具备的8个好习惯
Web开发者需具备的8个好习惯
程序员眼里IE浏览器是什么样的
程序员眼里IE浏览器是什么样的
那些性感的让人尖叫的程序员
那些性感的让人尖叫的程序员
 程序员的样子
程序员的样子
团队中“技术大拿”并非越多越好
团队中“技术大拿”并非越多越好
做程序猿的老婆应该注意的一些事情
做程序猿的老婆应该注意的一些事情
一个程序员的时间管理
一个程序员的时间管理
2013年中国软件开发者薪资调查报告
2013年中国软件开发者薪资调查报告
我跳槽是因为他们的显示器更大
我跳槽是因为他们的显示器更大
软件开发程序错误异常ExceptionCopyright © 2009-2015 MyException 版权所有