spring+mybatis 框架搭建

时间:2023-08-21 17:19:14

注意<!-- 中间的字要保持与左右留出一个空格,否则会报错说出现两杠线 -->

1.导入jar包

aopalliance-1.0.jar
asm-3.3.1.jar
cglib-2.2.2.jar
com.springsource.org.aspectj.weaver-1.6.8.RELEASE.jar
commons-logging-1.1.1.jar
javassist-3.17.1-GA.jar
junit-4.9.jar
log4j-1.2.17.jar
mybatis-3.0.3.jar
mybatis-3.2.2.jar
mybatis-spring-1.0.0-RC3.jar
mysql-connector-java-5.1.10-bin.jar
slf4j-api-1.7.5.jar
slf4j-log4j12-1.7.5.jar
spring-aop-3.0.5.RELEASE.jar
spring-asm-3.0.5.RELEASE.jar
spring-beans-3.0.5.RELEASE.jar
spring-context-3.0.5.RELEASE.jar
spring-core-3.0.5.RELEASE.jar
spring-expression-3.0.5.RELEASE.jar
spring-jdbc-3.0.5.RELEASE.jar
spring-tx-3.0.5.RELEASE.jar

2.写

src

----cn.itcast.mybatis.damain

          User.java

          User.xml

----cn.itcast.mybatis.dao

          IUserDao.java

          UserDaoImpl.java

----cn.itcast.mybatis.service

          IUserService

          UserServiceImpl

----spring-beans.xml

----sqlMapConfig.xml

User.java

package cn.itcast.mybatis.domain;

public class User {
    private String id;
    private String name;
    private Integer age;
    private String address;
    public String getAddress() {
        return address;
    }
    public void setAddress(String address) {
        this.address = address;
    }
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Integer getAge() {
        return age;
    }
    public void setAge(Integer age) {
        this.age = age;
    }
    @Override
    public String toString() {
        return "User [id=" + id + ", name=" + name + ", age=" + age + "]";
    }

}

User.xml

<?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="cn.itcast.mybatis.domain.User">
    <sql id="cols">
        id,name,age,address
    </sql>
    <sql id="ucols">
        name=#{name},age=#{age},address=#{address}
    </sql>

    <!-- 查询所有记录 -->
    <select id="listAll" resultType="aliasesUser">
        select <include refid="cols"/> from user_c
    </select>

    <!-- 按条件查询 -->
    <select id="find" parameterType="aliasesUser" resultType="aliasesUser">
        select * from user_c
        <where>
        <if test="name!=null">
            and name like "%"#{name}"%"
        </if>
        <if test="age!=null">
            and age=#{age}
        </if>
        </where>
    </select>

    <!-- 查询一个用户 -->
    <select id="get" parameterType="string" resultType="aliasesUser">
        select <include refid="cols"/> from user_c where id=#{id}
    </select>

    <!-- 新增 -->
    <insert id="create" parameterType="aliasesUser">
        insert into user_c (id,name,age,address) values(#{id},#{name},#{age},#{address})
    </insert>

    <!-- 修改 -->
    <update id="update" parameterType="aliasesUser">
        update user_c
         <set>
             <if test="name!=null">
                 name=#{name},
             </if>
             <if test="age!=null">
                 age=#{age},
             </if>
             <if test="address!=null">
                 address=#{address},
             </if>
         </set>

        where id=#{id}
    </update>

    <!-- 删除 -->
    <delete id="delete" parameterType="string">
        delete from user_c where id=#{id}
    </delete>
</mapper>

IUserDao.java

package cn.itcast.mybatis.dao;

import java.util.List;

import cn.itcast.mybatis.domain.User;

public interface IUserDao {
    public List<User> list();
    public User get(String id);
    public int insert(User u);
    public int update(User u);
    public int deleteById(String id);
}

UserDaoImpl.java

package cn.itcast.mybatis.dao;

import java.util.List;

import org.mybatis.spring.support.SqlSessionDaoSupport;

import cn.itcast.mybatis.domain.User;

public class UserDaoImpl extends SqlSessionDaoSupport implements IUserDao {

    //删除
    public int deleteById(String id) {
        return this.getSqlSession().delete("cn.itcast.mybatis.domain.User.deleteOne",id);
    }

    //新增
    public int insert(User u) {
        return this.getSqlSession().insert("cn.itcast.mybatis.domain.User.create", u);
    }

    //列表
    public List<User> list() {
        return this.getSqlSession().selectList("cn.itcast.mybatis.domain.User.listAll");
    }

    //修改
    public int update(User u) {
        return this.getSqlSession().update("cn.itcast.mybatis.domain.User.update",u);
    }

    //获取对象
    public User get(String id) {
        return (User) this.getSqlSession().selectOne("cn.itcast.mybatis.domain.User.get", id);
    }

}

UserServiceDao.java

package cn.itcast.mybatis.service;

import java.util.List;

import cn.itcast.mybatis.domain.User;

public interface IUserService {
    public List<User> list();
    public User get(String id);
    public int insert(User u);
    public int update(User u);
    public int deleteById(String id);
}

UserServiceDaoImpl.java

package cn.itcast.mybatis.service;

import java.util.List;

import cn.itcast.mybatis.dao.IUserDao;
import cn.itcast.mybatis.domain.User;

public class UserServiceImpl implements IUserService {

    private IUserDao userDao;
    public void setUserDao(IUserDao userDao) {
        this.userDao = userDao;
    }

    public int deleteById(String id) {
        int i = userDao.deleteById(id);
                //测试事务
        int j = 1/0;
        return i;
    }

    public User get(String id) {
        return userDao.get(id);
    }

    public int insert(User u) {
        return userDao.insert(u);
    }

    public List<User> list() {
        return userDao.list();
    }

    public int update(User u) {
        return userDao.update(u);
    }

}

重头

sqlMapConfig.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="cn.itcast.mybatis.domain.User" alias="aliasesUser"></typeAlias>
    </typeAliases>
 <environments default="development">

        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/mybatisdb?characterEncoding=UTF-8"/>
                <property name="username" value="root"/>
                <property name="password" value="friends"/>
            </dataSource>
        </environment>
<!--         产品    可用于多个配置的 -->
        <environment id="product">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/mybatisdb?characterEncoding=UTF-8"/>
                <property name="username" value="root"/>
                <property name="password" value="friends"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="cn/itcast/mybatis/domain/User.xml"/>
    </mappers>
</configuration>

spring-beans.xml

<?xml version="1.0" encoding="UTF-8"?>
<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-3.0.xsd
                         http://www.springframework.org/schema/context
                         http://www.springframework.org/schema/context/spring-context-3.0.xsd
                         http://www.springframework.org/schema/tx
                         http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
                         http://www.springframework.org/schema/aop
                         http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">

    <!-- 数据源 -->
    <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/mybatisdb?characterEncoding=utf-8"></property>
        <property name="username" value="root"></property>
        <property name="password" value="friends"></property>
    </bean>

    <bean id="sessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="configLocation" value="classpath:sqlMapConfig.xml"></property>
        <property name="dataSource" ref="dataSource"></property>

    </bean>

    <!-- 事务相关控制 -->
    <bean name="transactionManager"
        class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>

    <!-- 通知 -->
    <tx:advice id="tx"
        transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="delete*" propagation="REQUIRED" />
            <tx:method name="insert*" propagation="REQUIRED" />
            <tx:method name="update*" propagation="REQUIRED" />
            <tx:method name="find*" read-only="true" />
            <tx:method name="get*" read-only="true" />
            <tx:method name="select*" read-only="true" />
        </tx:attributes>
    </tx:advice>

    <aop:config>
        <aop:pointcut id="pc" expression="execution(* cn.itcast.mybatis.service.*.*(..))" />
        <!--把事务控制在Service层-->
        <aop:advisor pointcut-ref="pc" advice-ref="tx" />
    </aop:config>

    <bean id="userDao" class="cn.itcast.mybatis.dao.UserDaoImpl">
        <property name="sqlSessionFactory" ref="sessionFactory"></property>
    </bean>

    <bean id="userService" class="cn.itcast.mybatis.service.UserServiceImpl">
        <property name="userDao" ref="userDao"></property>
    </bean>
</beans>

测试

package test;

import java.util.List;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import cn.itcast.mybatis.domain.User;
import cn.itcast.mybatis.service.IUserService;

public class TestSpringMybatis {

    @Test
    public void test(){
        ApplicationContext ac = new ClassPathXmlApplicationContext("spring-beans.xml");
        IUserService us = (IUserService) ac.getBean("userService");
        List<User> users = us.list();
        System.out.println(users.size());
    }

    @Test
    public void testDelete(){
        ApplicationContext ac = new ClassPathXmlApplicationContext("spring-beans.xml");
        IUserService us = (IUserService) ac.getBean("userService");
        us.deleteById("1");
    }

}