框架第六次作业

本文详细介绍了一种基于MyBatis的数据访问层设计,包括用户表和订单表的查询实现。通过实体类、数据访问层接口及其实现、业务逻辑层接口及其实现等模块,实现了用户信息和订单信息的查询、添加、修改和删除等功能。

一、实现用户表查询

1.实体类

package com.oupeng.pojo;

import java.io.Serializable;
import java.util.Date;
import java.util.List;

public class User implements Serializable{
	private Integer id;
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	private String userCode; 
	public String getUserCode() {
		return userCode;
	}
	public void setUserCode(String userCode) {
		this.userCode = userCode;
	}
	private String userName; 
	private String userPassword; 
	private Integer gender; 
	private Date birthday; 
	private String phone; 
	private String  address;
	private Integer userRole;
	private Date creationDate ;
	private Integer createdBy; 
	private  Integer modifyBy;  
	private  String userRoleName;

	public String getUserRoleName() {
		return userRoleName;
	}
	public void setUserRoleName(String userRoleName) {
		this.userRoleName = userRoleName;
	}
	public Integer getModifyBy() {
		return modifyBy;
	}
	public void setModifyBy(Integer modifyBy) {
		this.modifyBy = modifyBy;
	}
	public Date getModifyDate() {
		return modifyDate;
	}
	public void setModifyDate(Date modifyDate) {
		this.modifyDate = modifyDate;
	}
	private Date modifyDate;  
	private String idPicPath;  
	
	public String getUserName() {
		return userName;
	}
	public void setUserName(String userName) {
		this.userName = userName;
	}
	public String getUserPassword() {
		return userPassword;
	}
	public void setUserPassword(String userPassword) {
		this.userPassword = userPassword;
	}
	public Integer getGender() {
		return gender;
	}
	public void setGender(Integer gender) {
		this.gender = gender;
	}
	public Date getBirthday() {
		return birthday;
	}
	public void setBirthday(Date birthday) {
		this.birthday = birthday;
	}
	public String getPhone() {
		return phone;
	}
	public void setPhone(String phone) {
		this.phone = phone;
	}
	public String getAddress() {
		return address;
	}
	public void setAddress(String address) {
		this.address = address;
	}
	public Integer getUserRole() {
		return userRole;
	}
	public void setUserRole(Integer userRole) {
		this.userRole = userRole;
	}
	public Date getCreationDate() {
		return creationDate;
	}
	public void setCreationDate(Date creationDate) {
		this.creationDate = creationDate;
	}
	public Integer getCreatedBy() {
		return createdBy;
	}
	public void setCreatedBy(Integer createdBy) {
		this.createdBy = createdBy;
	}
	
	public String getIdPicPath() {
		return idPicPath;
	}
	public void setIdPicPath(String idPicPath) {
		this.idPicPath = idPicPath;
	}
	public String getWorkPicPath() {
		return workPicPath;
	}
	public void setWorkPicPath(String workPicPath) {
		this.workPicPath = workPicPath;
	}
	private String workPicPath;
}

2.数据访问层接口

package com.oupeng.dao;

import java.util.List;

import org.apache.ibatis.annotations.Param;

import com.oupeng.pojo.User;

public interface UserMapper {
       //查询所有的用户
	public List<User> getUserList(User user);
	//插入用户
	public int add(User user);
	//根据用户id修改用户信息
	public int modify(User user);
	//删除用户
    public int deleteByUserId(@Param("id") Integer userId);
    //定义实现个人信息(密码)修改的功能
  	public int updatePwd(@Param("uid") Integer id,@Param("userPassword")String pwd);
}

配置文件

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
  PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  <!-- nameSpace相当于一个文件夹,用来找映射文件   接口  里面id和接口的方法名相同;resultType表示方法返回值-->
  
  <mapper namespace="com.oupeng.dao.UserMapper">
	<!-- 配置查询 -->
	<select id="getUserList" parameterType="User"
		resultMap="userList">
		select u.*, r.roleName from smbms_user u,smbms_role r where u.userName like
		concat('%',#{userName},'%') and u.userRole=#{userRole} and
		u.userRole=r.id
	</select>

	<resultMap type="User" id="userList">
		<result property="userCode" column="userCode" />
		<result property="userName" column="userName" />
		<result property="userRoleName" column="roleName" />
	</resultMap>
	<insert id="add" parameterType="User">
	insert into smbms_user(userCode,userName,gender,address)values(#{userCode},#{userName},#{gender},#{address})
   </insert>
   
   
    <!-- 修改用户 -->
  <update id="modify" parameterType="User">
  update smbms_user set userName=#{userName},userPassword=#{userPassword} where id=#{id}
  </update>
  
  <!-- 删除用户 -->
	<delete id="deleteByUserId" parameterType="Integer">
		delete from smbms_user where id=#{id}
	</delete>
	
	<!-- 实现个人密码修改 -->
	<update id="updatePwd">
	update smbms_user set userPassword=#{userPassword} where id=#{uid}
	</update>
  </mapper>

3数据访问层实体类

package com.oupeng.dao.impl;

import java.util.List;

import org.mybatis.spring.SqlSessionTemplate;

import com.oupeng.dao.UserMapper;
import com.oupeng.pojo.User;

public class UserMapperImpl implements UserMapper {
     //增加特殊的整合类:SqlSessionTemplate
	private SqlSessionTemplate sqlSession;
	public SqlSessionTemplate getSqlSession() {
		return sqlSession;
	}

	public void setSqlSession(SqlSessionTemplate sqlSession) {
		this.sqlSession = sqlSession;
	}

	@Override
	public List<User> getUserList(User user) {
		
		return sqlSession.selectList("com.oupeng.dao.UserMapper.getUserList",user);
	}

	@Override
	public int add(User user) {
		
		return sqlSession.insert("com.oupeng.dao.UserMapper.add",user);
	}

	@Override
	public int modify(User user) {
		return sqlSession.update("com.oupeng.dao.UserMapper.modify", user);
	}

	@Override
	public int deleteByUserId(Integer userId) {
		
		return sqlSession.delete("com.oupeng.dao.UserMapper.deleteByUserId",28);
	}

	@Override
	public int updatePwd(Integer id, String pwd) {
		
		return sqlSession.getMapper(UserMapper.class).updatePwd(id, pwd);
	}

}

4.业务逻辑层接口

package com.oupeng.dao;

import java.util.List;

import org.apache.ibatis.annotations.Param;

import com.oupeng.pojo.User;

public interface UserMapper {
       //查询所有的用户
	public List<User> getUserList(User user);
	//插入用户
	public int add(User user);
	//根据用户id修改用户信息
	public int modify(User user);
	//删除用户
    public int deleteByUserId(@Param("id") Integer userId);
    //定义实现个人信息(密码)修改的功能
  	public int updatePwd(@Param("uid") Integer id,@Param("userPassword")String pwd);
}

5.业务逻辑层实体类

package com.oupeng.service.impl;

import java.util.List;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.oupeng.dao.UserMapper;
import com.oupeng.pojo.User;
import com.oupeng.service.UserService;

//@Transactional
//@Service("userService1")
public class UserServiceImpl implements UserService {

	//注入数据访问层依赖(写接口松耦合,面向接口编程)
	//@Autowired
	private UserMapper userMapper;
	//@Transactional(propagation = Propagation.REQUIRED)
	public UserMapper getUserMapper() {
		return userMapper;
	}

	public void setUserMapper(UserMapper userMapper) {
		this.userMapper = userMapper;
	}

	@Override
	public List<User> findUserList(User user) {
		
		return userMapper.getUserList(user);
	}

	@Override
	public boolean addNewUser(User user) {
	    int result=userMapper.add(user);
		return result>0;
	}

	@Override
	public int modify(User user) {
		
		return userMapper.modify(user);
	}

	@Override
	public int deleteByUserId(Integer userId) {
		
		return userMapper.deleteByUserId(userId);
	}

	@Override
	public int updatePwd(Integer id, String pwd) {
		
		return userMapper.updatePwd(id, pwd);
	}

}

6.配置
MyBatis-config.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
  PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-config.dtd">

<configuration>
	<!-- 给类起别名 -->
	<typeAliases>
		<!-- <typeAlias type="com.oupeng.pojo.User" alias="User"/> -->
		<package name="com.oupeng.pojo" />
	</typeAliases>
	
</configuration>

事务配置

<!-- 配置spring的事务管理器 -->
	<bean id="transactionManager"
		class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<!-- 注入数据源 -->
		<property name="dataSource" ref="dataSource"></property>
	</bean>

	<!-- 配置事务管理策略 transaction-manager="transactionManager的值和事务管理器的id保持一致 -->
	<tx:advice id="txadvice" transaction-manager="transactionManager">
		<!-- 配置具体的策略 -->
		<tx:attributes>
		<!-- 增删改查的方法 timeout="10"超时时间,-1指的是无限 rollback-for遇到?允许回滚 -->
              <tx:method name="get*" propagation="REQUIRED" timeout="10"/>
              <tx:method name="add*" propagation="REQUIRES_NEW" rollback-for="SQLException"/>
              <tx:method name="update*" propagation="REQUIRED" timeout="10"/> 
              <tx:method name="delte*" propagation="REQUIRED" timeout="10"/>
		</tx:attributes>
	</tx:advice>
	
	<!-- 事务策略的配置应用 -->
	<aop:config>
	<!--  配置切入点  -->
	<aop:pointcut expression="execution(* com.oupeng.service..*.*(..))" id="p1"/>
	<!--  增强处理  -->
	<aop:advisor advice-ref="txadvice" pointcut-ref="p1"/> 
		</aop:config>
		
		
		<!--启用事务注解 -->
		 <!-- <tx:annotation-driven transaction-manager="transactionManager"/>  -->

配置数据源

<!-- 配置数据源 -->
<!-- <bean id="dataSource"
	class="org.apache.commons.dbcp.BasicDataSource">
	<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
	<property name="url"
		value="jdbc:mysql://127.0.0.1:3306/smbms?useUnicode=true&amp;characterEncoding=utf-8"></property>
	<property name="username" value="root"></property>
	<property name="password" value="root"></property>

</bean> -->

	<!-- 配置数据源方式2 -->
	<bean
		class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
		<property name="Location">
			<value>classpath:database.properties</value>
		</property>

	</bean>

	<bean id="dataSource"
		class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
		<property name="driverClassName" value="${jdbc.driver}"></property>
		<property name="url" value="${jdbc.url}"></property>
		<property name="password" value="${jdbc.password}"></property>
		<property name="username" value="${jdbc.username}"></property>
	</bean>

方法一:
使用sqlSessionTemplate

<!-- 配置数据访问层组件 -->
	<bean id="userMapper" class="com.oupeng.dao.impl.UserMapperImpl">
		<!-- 注入sqlSessionTemplate -->
		<property name="sqlSession" ref="sqlSessionTemplate"></property>
	</bean>
<!-- 业务逻辑层组件 -->
	<bean id="userService" class="com.oupeng.service.impl.UserServiceImpl"
		autowire="byName">
		<!-- 完成数据访问层对象的注入 -->
		<!-- <property name="userMapper" ref="userMapper"></property> <property 
			name="userMapper" ref="userMapperProxy"></property> -->
	</bean>
	<!-- 加载拆分的配置文件 -->
	<import resource="applicationContext-dao.xml"/>
	<import resource="applicationContext-service.xml"/>
	<bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
<!-- 构造注入sqlSessionFactory -->
 <constructor-arg name="sqlSessionFactory" ref="sqlSessionFactory"></constructor-arg>
</bean>

方法二

<bean id="userService" class="com.oupeng.service.impl.UserServiceImpl"
		autowire="byName">
		<!-- 完成数据访问层对象的注入 -->
		<!-- <property name="userMapper" ref="userMapper"></property>  -->
		<property name="userMapper" ref="userMapperProxy"></property>
	</bean>
	<import resource="applicationContext-service.xml"/>
	<bean id="userMapperProxy" class="org.mybatis.spring.mapper.MapperFactoryBean">
<property name="mapperInterface" value="com.oupeng.dao.UserMapper"></property>
<property name="sqlSessionFactory" ref="sqlSessionFactory"></property>

</bean>

方法三注解


<!-- 自动扫描这个包下所有接口 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
       <property name="basePackage" value="com.oupeng.dao"></property>
		<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
</bean>

<!--配置让其自动扫码指定的包下的注解  -->
	<context:component-scan base-package="com.oupeng.service.impl"></context:component-scan>
<!-- 配置spring的事务管理器 -->
	<bean id="transactionManager"
		class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<!-- 注入数据源 -->
		<property name="dataSource" ref="dataSource"></property>
	</bean>
	<tx:annotation-driven transaction-manager="transactionManager"/> 
	
@Transactional
@Service("userService1")
public class UserServiceImpl implements UserService {

	//注入数据访问层依赖(写接口松耦合,面向接口编程)
     @Autowired
	private UserMapper userMapper;
	//@Transactional(propagation = Propagation.REQUIRED)
	public UserMapper getUserMapper() {
		return userMapper;
	}

	public void setUserMapper(UserMapper userMapper) {
		this.userMapper = userMapper;
	}

	@Override
	public List<User> findUserList(User user) {
		
		return userMapper.getUserList(user);
	}

	@Override
	public boolean addNewUser(User user) {
	    int result=userMapper.add(user);
		return result>0;
	}

	//@Transactional(propagation = Propagation.REQUIRED)
	public int modify(User user) {
		
		return userMapper.modify(user);
	}

	//@Transactional(propagation = Propagation.REQUIRED)
	public int deleteByUserId(Integer userId) {
		
		return userMapper.deleteByUserId(userId);
	}

	//@Transactional(propagation = Propagation.REQUIRED)
	public int updatePwd(Integer id, String pwd) {
		
		return userMapper.updatePwd(id, pwd);
	}

}

7 测试类

 @Test
        public void testmodify() {
        	ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");
            UserService us=(UserService) context.getBean("userService");
    		User user=new User();
    		user.setId(28);
    		user.setUserName("王五");
    		user.setUserPassword("123457896");
    		int result=us.modify(user);
    		
    		if(result>0) {
    			System.out.println("修改成功");
    		}else {
				System.out.println("修改失败");
			}
		
    		
        }
        @Test
        public void testdelete() {
        	ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");
            UserService us=(UserService) context.getBean("userService");
    		
    		int result=us.deleteByUserId(28);
    		
    		if(result>0) {
    			System.out.println("删除成功");
    		}else {
				System.out.println("删除失败");
			}
		
    		
        }
        
        @Test
        public void testupdatePwd() {
        	ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");
            UserService us=(UserService) context.getBean("userService");
    		
    		int result=us.updatePwd(29, "123456");
    		
    		if(result>0) {
    			System.out.println("密码修改成功");
    		}else {
				System.out.println("密码修改失败");
			}
		
    		
        }

执行结果
代码结果执行一样
在这里插入图片描述

二、实现订单表查询

1、实体类

package com.oupeng.pojo;

import java.math.BigDecimal;
import java.util.Date;

public class Bill {
       private Integer id;
       private String billCode;
       private String productName;
       private String productDesc;
       private String productUnit;
       private BigDecimal productCount;
       private BigDecimal totalPrice;
       private int isPayment;
       private Integer createdBy;
       private Date creationDate;
       private Integer modifyBy;
       private Date modifyDate;
       private Integer providerId;
       private String providerName;  //供应商名称
	
	public String getProviderName() {
		return providerName;
	}
	public void setProviderName(String providerName) {
		this.providerName = providerName;
	}
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getBillCode() {
		return billCode;
	}
	public void setBillCode(String billCode) {
		this.billCode = billCode;
	}
	public String getProductName() {
		return productName;
	}
	public void setProductName(String productName) {
		this.productName = productName;
	}
	public String getProductDesc() {
		return productDesc;
	}
	public void setProductDesc(String productDesc) {
		this.productDesc = productDesc;
	}
	public String getProductUnit() {
		return productUnit;
	}
	public void setProductUnit(String productUnit) {
		this.productUnit = productUnit;
	}
	public BigDecimal getProductCount() {
		return productCount;
	}
	public void setProductCount(BigDecimal productCount) {
		this.productCount = productCount;
	}
	public BigDecimal getTotalPrice() {
		return totalPrice;
	}
	public void setTotalPrice(BigDecimal totalPrice) {
		this.totalPrice = totalPrice;
	}
	public int getIsPayment() {
		return isPayment;
	}
	public void setIsPayment(int isPayment) {
		this.isPayment = isPayment;
	}
	public Integer getCreatedBy() {
		return createdBy;
	}
	public void setCreatedBy(Integer createdBy) {
		this.createdBy = createdBy;
	}
	public Date getCreationDate() {
		return creationDate;
	}
	public void setCreationDate(Date creationDate) {
		this.creationDate = creationDate;
	}
	public Integer getModifyBy() {
		return modifyBy;
	}
	public void setModifyBy(Integer modifyBy) {
		this.modifyBy = modifyBy;
	}
	public Date getModifyDate() {
		return modifyDate;
	}
	public void setModifyDate(Date modifyDate) {
		this.modifyDate = modifyDate;
	}
	public Integer getProviderId() {
		return providerId;
	}
	public void setProviderId(Integer providerId) {
		this.providerId = providerId;
	}
       
}

2、数据访问层接口

package com.oupeng.dao;

import java.util.List;

import com.oupeng.pojo.Bill;
import com.oupeng.pojo.User;

public interface BillMapper {
	  //查询所有
	public List<Bill> getBill();
		//根据商品名称,供应商Id,是否付款查询订单表
	public List<Bill> getBillList(Bill bill);
	//添加操作
	public int addBill(Bill bill);
	//根据id修改信息
	public int updateBill(Integer id) ;
	//根据id删除订单信息
	public int delteBill(Integer id);
}

配置

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
  PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
 
  
  
   <mapper namespace="com.oupeng.dao.BillMapper">
   
    <select id="getBill" resultType="Bill">
    select * from smbms_bill
  </select>
   
   
   
   <select id="getBillList" resultType="Bill" parameterType="Bill"  resultMap="ProviderList">
     select b.*,p.proName from smbms_bill b,smbms_provider p where b.productName like concat('%',#{productName},'%') 
     and b.providerId=#{providerId} and b.providerId=p.id and b.isPayment=#{isPayment}

</select>
  <resultMap type="Bill" id="ProviderList">
   <id property="id" column="id"/>
   <result property="billCode" column="billCode"/>
   <result property="productName" column="productName"/>
   <result property="productCount" column="productCount"/>
   <result property="isPayment" column="isPayment"/>
   <result property="creationDate" column="creationDate"/>
    <result property="providerName" column="proName"/>
  </resultMap>
  
  
  <insert id="addBill" parameterType="Bill">
	insert into smbms_bill(billCode,productName,productUnit,providerId)values(#{billCode},#{productName},#{productUnit},#{providerId})
   </insert>
   
   
   
  <update id="updateBill" parameterType="Bill">
  update smbms_bill set productName=#{productName},productUnit=#{productUnit} where id=#{id}
  </update>
  
  
	<delete id="deleteBill" parameterType="Integer">
		delete from smbms_user where id=#{id}
	</delete>
  
  
   </mapper>

3.数据访问层实现类

package com.oupeng.dao.impl;

import java.util.List;

import org.mybatis.spring.SqlSessionTemplate;

import com.oupeng.dao.BillMapper;
import com.oupeng.pojo.Bill;

public class BillMapperImpl implements BillMapper {
 public SqlSessionTemplate getSqlSession() {
		return sqlSession;
	}
	public void setSqlSession(SqlSessionTemplate sqlSession) {
		this.sqlSession = sqlSession;
	}
private SqlSessionTemplate sqlSession;
	@Override
	public List<Bill> getBillList(Bill bill) {
		
		return sqlSession.selectList("com.oupeng.dao.BillMapper.getBillList",bill);
	}
	@Override
	public List<Bill> getBill() {
		
		return sqlSession.selectList("com.oupeng.dao.BillMapper.getBill");
	}
	@Override
	public int addBill(Bill bill) {
		
		return sqlSession.insert("com.oupeng.dao.BillMapper.getBill",bill);
	}
	@Override
	public int updateBill(Integer id) {
		
		return sqlSession.update("com.oupeng.dao.BillMapper.updateBill",id);
	}
	@Override
	public int delteBill(Integer id) {
		
		return sqlSession.delete("com.oupeng.dao.BillMapper.deleteBill",id);
	}

}

4业务逻辑层

package com.oupeng.service;

import java.util.List;

import com.oupeng.pojo.Bill;

public interface BillService {
	//查询所有数据
	   public List<Bill> getBill();
		public List<Bill> getBillList(Bill bill);
		//添加操作
		public int addBill(Bill bill);
		//根据id修改信息
		public int updateBill(Integer id) ;
		//根据id删除订单信息
		public int delteBill(Integer id);
}

5 业务逻辑层实现类

package com.oupeng.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.oupeng.dao.BillMapper;
import com.oupeng.pojo.Bill;
import com.oupeng.service.BillService;
@Service("billService")
public class BillServiceImpl implements BillService {
     @Autowired
	private BillMapper billMapper;
	
	public BillMapper getBillMapper() {
		return billMapper;
	}

	public void setBillMapper(BillMapper billMapper) {
		this.billMapper = billMapper;
	}

	@Override
	public List<Bill> getBillList(Bill bill) {
		
		return billMapper.getBillList(bill);
	}

	@Override
	public List<Bill> getBill() {
		
		return billMapper.getBill();
	}

	@Transactional(propagation = Propagation.REQUIRED)
	@Override
	public int addBill(Bill bill) {
		
		return billMapper.addBill(bill);
	}
	@Transactional(propagation = Propagation.REQUIRED)
	@Override
	public int updateBill(Integer id) {
		
		return billMapper.updateBill(id);
	}
	@Transactional(propagation = Propagation.REQUIRED)
	@Override
	public int delteBill(Integer id) {
		
		return billMapper.delteBill(id);
	}

}

6 配置
MyBatis-config.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
  PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-config.dtd">

<configuration>
	<!-- 给类起别名 -->
	<typeAliases>
		<!-- <typeAlias type="com.oupeng.pojo.User" alias="User"/> -->
		<package name="com.oupeng.pojo" />
	</typeAliases>
	
</configuration>

事务配置

<!-- 配置spring的事务管理器 -->
	<bean id="transactionManager"
		class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<!-- 注入数据源 -->
		<property name="dataSource" ref="dataSource"></property>
	</bean>

	<!-- 配置事务管理策略 transaction-manager="transactionManager的值和事务管理器的id保持一致 -->
	<tx:advice id="txadvice" transaction-manager="transactionManager">
		<!-- 配置具体的策略 -->
		<tx:attributes>
		<!-- 增删改查的方法 timeout="10"超时时间,-1指的是无限 rollback-for遇到?允许回滚 -->
              <tx:method name="get*" propagation="REQUIRED" timeout="10"/>
              <tx:method name="add*" propagation="REQUIRES_NEW" rollback-for="SQLException"/>
              <tx:method name="update*" propagation="REQUIRED" timeout="10"/> 
              <tx:method name="delte*" propagation="REQUIRED" timeout="10"/>
		</tx:attributes>
	</tx:advice>
	
	<!-- 事务策略的配置应用 -->
	<aop:config>
	<!--  配置切入点  -->
	<aop:pointcut expression="execution(* com.oupeng.service..*.*(..))" id="p1"/>
	<!--  增强处理  -->
	<aop:advisor advice-ref="txadvice" pointcut-ref="p1"/> 
		</aop:config>
		
		
		<!--启用事务注解 -->
		 <!-- <tx:annotation-driven transaction-manager="transactionManager"/>  -->

配置数据源

<!-- 配置数据源 -->
<!-- <bean id="dataSource"
	class="org.apache.commons.dbcp.BasicDataSource">
	<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
	<property name="url"
		value="jdbc:mysql://127.0.0.1:3306/smbms?useUnicode=true&amp;characterEncoding=utf-8"></property>
	<property name="username" value="root"></property>
	<property name="password" value="root"></property>

</bean> -->

	<!-- 配置数据源方式2 -->
	<bean
		class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
		<property name="Location">
			<value>classpath:database.properties</value>
		</property>

	</bean>

	<bean id="dataSource"
		class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
		<property name="driverClassName" value="${jdbc.driver}"></property>
		<property name="url" value="${jdbc.url}"></property>
		<property name="password" value="${jdbc.password}"></property>
		<property name="username" value="${jdbc.username}"></property>
	</bean>

方法1:注解

<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
       <property name="basePackage" value="com.oupeng.dao"></property>
		<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
</bean>

<!--配置让其自动扫码指定的包下的注解  -->
	<context:component-scan base-package="com.oupeng.service.impl"></context:component-scan>
	<!-- 配置spring的事务管理器 -->
	<bean id="transactionManager"
		class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<!-- 注入数据源 -->
		<property name="dataSource" ref="dataSource"></property>
	</bean>
	<tx:annotation-driven transaction-manager="transactionManager"/> 
	<!--启用事务注解 -->
		 <tx:annotation-driven transaction-manager="transactionManager"/> 

package com.oupeng.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.oupeng.dao.BillMapper;
import com.oupeng.pojo.Bill;
import com.oupeng.service.BillService;
@Service("billService")
public class BillServiceImpl implements BillService {
     @Autowired
	private BillMapper billMapper;
	
	public BillMapper getBillMapper() {
		return billMapper;
	}

	public void setBillMapper(BillMapper billMapper) {
		this.billMapper = billMapper;
	}

	@Override
	public List<Bill> getBillList(Bill bill) {
		
		return billMapper.getBillList(bill);
	}

	@Override
	public List<Bill> getBill() {
		
		return billMapper.getBill();
	}

	@Transactional(propagation = Propagation.REQUIRED)
	@Override
	public int addBill(Bill bill) {
		
		return billMapper.addBill(bill);
	}
	@Transactional(propagation = Propagation.REQUIRED)
	@Override
	public int updateBill(Integer id) {
		
		return billMapper.updateBill(id);
	}
	@Transactional(propagation = Propagation.REQUIRED)
	@Override
	public int delteBill(Integer id) {
		
		return billMapper.delteBill(id);
	}

}

方法二:

<bean id="billService"
	class="com.oupeng.service.impl.BillServiceImpl">
	<!-- 完成数据访问层对象的注入 -->
	<!-- <property name="billMapper" ref="billMapper"></property> -->
	<property name="billMapper" ref="billMapperProxy"></property>
</bean> 
<import resource="applicationContext-service.xml"/>
<bean id="billMapperProxy" class="org.mybatis.spring.mapper.MapperFactoryBean">
<property name="mapperInterface" value="com.oupeng.dao.BillMapper"></property>
<property name="sqlSessionFactory" ref="sqlSessionFactory"></property>

</bean>

方法三

	<bean id="billMapper" class="com.oupeng.dao.impl.BillMapperImpl">
<!-- 注入sqlSessionTemplate --> 
<property name="sqlSession" ref="sqlSessionTemplate"></property>
</bean> 
<bean id="billService"
	class="com.oupeng.service.impl.BillServiceImpl">
	<!-- 完成数据访问层对象的注入 -->
	<property name="billMapper" ref="billMapper"></property>
	<!-- <property name="billMapper" ref="billMapperProxy"></property> -->
</bean> 

<import resource="applicationContext-dao.xml"/>
	<import resource="applicationContext-service.xml"/>
	<bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
<!-- 构造注入sqlSessionFactory -->
 <constructor-arg name="sqlSessionFactory" ref="sqlSessionFactory"></constructor-arg>
</bean>

测试

        @Test
        public void testaddBill() {
        	ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");
        	 BillService bs=(BillService) context.getBean("billService");
            Bill bill=new Bill();
            bill.setBillCode("sjwiwhihyygygu");
            bill.setProductName("哈哈");
            bill.setProductUnit("只");
            bill.setProviderId(12);
            int result=bs.addBill(bill);
            if(result>0) {
            	System.out.println("添加成功");
            }else {
            	System.out.println("添加失败");
            }
	
        }
        
        
        
        @Test
        public void testupdataBill() {
        	ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");
        	 BillService bs=(BillService) context.getBean("billService");
            int result=bs.updateBill(18);
            if(result>0) {
            	System.out.println("修改成功");
            }else {
            	System.out.println("修改失败");
            }
	
        }
        
        
        
        @Test
        public void testdetelBill() {
        	ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");
        	 BillService bs=(BillService) context.getBean("billService");
            int result=bs.delteBill(20);
            if(result>0) {
            	System.out.println("删除成功");
            }else {
            	System.out.println("删除失败");
            }
	
        }

执行结果
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值