**Spring4.3+MyBatis 3.3.1 项目整合**


一:获取Spring和MyBatis:
1:去Github下载Spring和MyBatis JAR 。
2:用eclipse或MyEclipse创建Maven项目。
本文将根据第一种方式创建普通Web项目,去Github下载Spring和MyBatis JAR加载到项目。


二:创建项目结构:
创建完成的项目结构

注:图片为创建完成的项目结构。
1:选择Jar:

Jar
将Jar导入工程。
三:编写一个简单的Test结构:

1:创建LDUser 数据表:
-- Create table
create table LDUSER
(
  LOGNID   VARCHAR2(20) not null,
  PASSWORD VARCHAR2(20) not null,
  USERNAME VARCHAR2(20) not null,
  STATE    CHAR(1) not null,
  POWER    CHAR(1) not null
)

-- Add comments to the columns 
comment on column C##LISDATA.LDUSER.LOGNID
  is '登录名';
comment on column C##LISDATA.LDUSER.PASSWORD
  is '密码';
comment on column C##LISDATA.LDUSER.USERNAME
  is '用户名';
comment on column C##LISDATA.LDUSER.STATE
  is '状态:[0:可用;1:失效]';
comment on column C##LISDATA.LDUSER.POWER
  is '权限,详细权限见数据字典权限type:power指定权限类型';
-- Create/Recreate primary, unique and foreign key constraints 
alter table LDUSER  add constraint PK_LOGINID primary key (LOGNID);
2:创建com.Fir.entity 在包下创建LDUser.java
package com.Fir.entity;

/**
 * User information entity class
 * @author AnGo
 *
 */
public class LDUser {

    //登录名
    private String LognID;
    //密码
    private String PassWord;
    //用户名
    private String UserName;
    //状态:[0:可用;1:失效]
    private String State;
    //权限,详细权限见数据字典权限type:power指定权限类型
    private String Power;


    public String getLognID() {
        return LognID;
    }
    public void setLognID(String lognID) {
        LognID = lognID;
    }
    public String getPassWord() {
        return PassWord;
    }
    public void setPassWord(String passWord) {
        PassWord = passWord;
    }
    public String getUserName() {
        return UserName;
    }
    public void setUserName(String userName) {
        UserName = userName;
    }
    public String getState() {
        return State;
    }
    public void setState(String state) {
        State = state;
    }
    public String getPower() {
        return Power;
    }
    public void setPower(String power) {
        Power = power;
    }

    public LDUser() {
        super();
        // TODO Auto-generated constructor stub
    }

    public LDUser(String lognID, String passWord, String userName, String state, String power) {
        super();
        LognID = lognID;
        PassWord = passWord;
        UserName = userName;
        State = state;
        Power = power;
    }



}
3:创建com.Fir.Service 在包下创建LDUserService.java
package com.Fir.Service;

import java.util.List;

import com.Fir.entity.LDUser;

/**
 * 业务类
 * @author AnGo
 *
 */
public interface LDUserService {

    // 插入一条
    void save(LDUser tLDUser);

    // 修改数据
    boolean update(LDUser tLDUser);

    // 删除数据
    boolean delete(LDUser tLDUser);

    // 查询一条数据
    LDUser findById(String LognID);

    // 获取所有的数据
    List<LDUser> findAll();
}
4:创建com.Fir.Dao 在包下创建LDUserDao.java
package com.Fir.Dao;

import java.util.List;

import com.Fir.entity.LDUser;

/**
 * 数据访问层接口
 * @author AnGo
 *
 */
public interface LDUserDao {

    //插入一条
    void save(LDUser tLDUser);
    //修改数据
    boolean update(LDUser tLDUser);
    //删除数据
    boolean delete(LDUser tLDUser);
    //查询一条数据
    LDUser findById(String LognID);
    //获取所有的数据
    List<LDUser> findAll();
}
5:创建jdbc.properties (数据连接配置)
jdbc.driver=oracle.jdbc.driver.OracleDriver
jdbc.url=jdbc\:oracle\:thin\:@localhost\:1521\:orcl
jdbc.UserName=C\#\#lis
jdbc.PassWord=lis
6:创建com.Fir.Dao 在包下创建LDUserMapper.xml (SQL映射文件)
<?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.Fir.Dao.LDUserDao">
    <insert id="save" parameterType="LDUser">
        insert into LDUser(LognID,PassWord,UserName,State,Power)
        values(#{LognID},#{PassWord},#{UserName},#{State},#{Power})
    </insert>

    <update id="update" parameterType="LDUser">
        update LDUser set LognID=#{LognID},PassWord=#{PassWord} 
        where UserName=#{UserName}
    </update>

    <delete id="delete" parameterType="LDUser">
        delete from LDUser where LognID=#{LognID} and PassWord=#{PassWord} 
    </delete>

    <!-- mybsits_config中配置的alias类别名,也可直接配置resultType为类路径(com.Fir.entity.LDUser) -->  
    <select id="findById" parameterType="string" resultType="LDUser">
        select * from LDUser where LognID=#{LognID}
    </select>

    <select id="findAll" resultType="LDUser">
        select * from LDUser
    </select>

</mapper>
7:创建Mybatis_Config.xml (MyBatis核心配置文件)
<?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.Fir.entity.LDUser" alias="LDUser"/>
    </typeAliases>

    <!-- 映射器 -->
    <mappers>
        <mapper resource="com/Fir/Dao/LDUserMapper.xml"/>
    </mappers>
</configuration>
8:创建com.Fir.Service.impl 在包下创建LDUserService_Impl.java
package com.Fir.Service.impl;


import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

import com.Fir.Dao.LDUserDao;
import com.Fir.Service.LDUserService;
import com.Fir.entity.LDUser;

/**
 * 业务实现类
 * @author AnGo
 *
 */
public class LDUserService_Impl implements LDUserService {

    //Spring自动注入,稍后编写SpringBase
    @Autowired @Qualifier("LDUserDao")
    public LDUserDao tLDUserDao;

    @Override
    public void save(LDUser tLDUser) {
        // TODO Auto-generated method stub
        tLDUserDao.save(tLDUser);
    }

    @Override
    public boolean update(LDUser tLDUser) {
        // TODO Auto-generated method stub
        return tLDUserDao.update(tLDUser);
    }

    @Override
    public boolean delete(LDUser tLDUser) {
        // TODO Auto-generated method stub
        return tLDUserDao.delete(tLDUser);
    }

    @Override
    public LDUser findById(String LognID) {
        // TODO Auto-generated method stub
        return tLDUserDao.findById(LognID);
    }

    @Override
    public List<LDUser> findAll() {
        // TODO Auto-generated method stub
        return tLDUserDao.findAll();
    }



}
9:创建com.Fir.Dao.impl 在包下创建LDUserDao_Impl.java
package com.Fir.Dao.impl;

import java.util.List;

import org.mybatis.spring.support.SqlSessionDaoSupport;

import com.Fir.Dao.LDUserDao;
import com.Fir.entity.LDUser;

/**
 * 数据访问层实现类
 * @author AnGo
 *
 */
public class LDUserDao_Impl extends SqlSessionDaoSupport implements LDUserDao {

    @Override
    public void save(LDUser tLDUser) {
        // TODO Auto-generated method stub
        System.out.println(this.getSqlSession().insert("save",tLDUser));
    }

    @Override
    public boolean update(LDUser tLDUser) {
        // TODO Auto-generated method stub
        int tFlag = this.getSqlSession().update("update",tLDUser);

        if(tFlag>0){
            return true;
        }else{
            return false;
        }
    }

    @Override
    public boolean delete(LDUser tLDUser) {
        // TODO Auto-generated method stub
        int tFlag = this.getSqlSession().update("delete",tLDUser);

        if(tFlag>0){
            return true;
        }else{
            return false;
        }

    }

    @Override
    public LDUser findById(String LognID) {
        // TODO Auto-generated method stub
        LDUser tLdUser = this.getSqlSession().selectOne("findById",LognID);
        return tLdUser;
    }

    @Override
    public List<LDUser> findAll() {
        // TODO Auto-generated method stub
        List<LDUser> tList = this.getSqlSession().selectList("findAll");
        return tList;
    }

}
10:创建Spring_BaseConfig.xml (Spring核心文件,管理MyBatis以及事物控制、数据访问)
<?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:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context" 
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-4.3.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx-4.3.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop-4.3.xsd ">

    <!-- 自动加载 -->
    <context:component-scan base-package="com.Fir"/>
    <!-- 1.读取Properties配置文件 -->
    <context:property-placeholder location="jdbc.properties"/>
    <!-- 2. 数据源 : DriverManagerDataSource -->
    <bean id="dataSource" 
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="${jdbc.driver}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.UserName}"/>
        <property name="password" value="${jdbc.PassWord}"/>
    </bean>

    <!--
        3. mybatis的SqlSession的工厂: SqlSessionFactoryBean dataSource:引用数据源 ,MyBatis定义数据源
    -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="configLocation" value="classpath:Mybatis_Config.xml" /> 
    </bean>
    <!--
        4. 事务管理 : DataSourceTransactionManager dataSource:引用上面定义的数据源
    -->
    <bean id="txManager"
        class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"></property>
    </bean>

    <!-- 5. 事务
         transaction-manager:引用上面定义的事务管理器
     -->
    <tx:advice id="txAdvice" transaction-manager="txManager">
        <tx:attributes>
            <tx:method name="get*" propagation="REQUIRED"
                read-only="true" />
            <tx:method name="find*" propagation="REQUIRED"
                read-only="true" />
            <tx:method name="search*" propagation="REQUIRED"
                read-only="true" />
            <tx:method name="query*" propagation="REQUIRED"
                read-only="true" />
            <tx:method name="add*" propagation="REQUIRED" />
            <tx:method name="submit*" propagation="REQUIRED" />
            <tx:method name="save*" propagation="REQUIRED" />
            <tx:method name="insert*" propagation="REQUIRED" />
            <tx:method name="del*" propagation="REQUIRED" />
            <tx:method name="remove*" propagation="REQUIRED" />
            <tx:method name="update*" propagation="REQUIRED" />
            <tx:method name="modify*" propagation="REQUIRED" />
            <tx:method name="check*" propagation="REQUIRED" />
            <tx:method name="do*" propagation="REQUIRED" />
            <tx:method name="*" propagation="REQUIRED" read-only="true" />
        </tx:attributes>
        </tx:advice>
    <!-- 6. Dao注入 -->
    <bean id="LDUserDao" class="com.Fir.Dao.impl.LDUserDao_Impl">  
        <property name="SqlSessionFactory" ref="sqlSessionFactory"></property>
    </bean>

    <!-- 7. Service注入 -->
    <bean id="LDUserService" class="com.Fir.Service.impl.LDUserService_Impl"/>  

    <!-- 8. 事务方式放在Service层控制 -->
    <aop:config>
        <aop:pointcut id="serviceMethod"
            expression="execution(* com.Fir.Service.*.*(..))" />
        <aop:advisor advice-ref="txAdvice" pointcut-ref="serviceMethod" />
    </aop:config>
</beans>
11:创建com.Fir.test 在包下创建test_001.java   (测试类001)
package com.Fir.test;

import java.util.List;

import org.apache.log4j.Logger;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.Fir.Service.LDUserService;
import com.Fir.entity.LDUser;

/**
 * 测试类001
 * @author AnGo
 *
 */
public class test_001 {

    Logger mLogger = Logger.getLogger(test_001.class);

    @Test
    public void test(){
        ApplicationContext ctx=new ClassPathXmlApplicationContext("classpath:Spring_BaseConfig.xml");  
        LDUserService tLDUserService = (LDUserService) ctx.getBean("LDUserService");

        String tLognID = "";
        LDUser tLdUser = tLDUserService.findById(tLognID);
        System.out.println(tLdUser.getUserName());

//      List<LDUser> tLis =tLDUserService.findAll();
//      
//      System.out.println(tLis.size());

    }


}

这里写图片描述


【本文非作者同意禁止转载】

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值