关于spring:spring框架和Mybatis框架整合依葫芦画瓢的题解

35次阅读

共计 8978 个字符,预计需要花费 23 分钟才能阅读完成。

1、题目形容

2、参考解答

com.controller 包下的 BookController.java

package com.controller;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import com.dao.BookDao;
import com.po.MyBook;
@Controller("bookController")
public class BookController {
    @Autowired
    private BookDao bookDao;
    public void test() {
        // 查问一条书籍记录
        MyBook abook = bookDao.selectBookBySN(1);
        System.out.println(abook);
        System.out.println("================");
        // 增加一条书籍记录
        MyBook addmb = new MyBook();
        addmb.setBookName("西游记");
        addmb.setBookPrice((float) 24.6);
        int add = bookDao.addBook(addmb);
        System.out.println("增加了" + add + "条记录");
        System.out.println("================");
        // 批改一条书籍记录
        MyBook updatemb = new MyBook();
        updatemb.setSn(1);
        updatemb.setBookName("红楼梦");
        updatemb.setBookPrice((float) 35.3);
        int up = bookDao.updateBook(updatemb);
        System.out.println("批改了" + up + "条记录");
        System.out.println("================");
        // 删除一条书籍记录
        int dl = bookDao.deleteBook(9);
        System.out.println("删除了" + dl + "条记录");
        System.out.println("================");
        // 查问所有书籍记录
        List<MyBook> list = bookDao.selectAllBook();
        for (MyBook myBook : list) {System.out.println(myBook);
        }
    }
}

com.controller 包下的 TestController.java

package com.controller;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestController {public static void main(String[] args) {ApplicationContext appCon = new ClassPathXmlApplicationContext("applicationContext.xml");
        BookController bc = (BookController)appCon.getBean("bookController");
        bc.test();}
}

com.dao 包下的 BookDao.java

package com.dao;
import java.util.List;

import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;
import com.po.MyBook;
@Repository("bookDao")
@Mapper
/* 应用 Spring 主动扫描 MyBatis 的接口并拆卸(Spring 将指定包中所有被 @Mapper 注解标注的接口主动拆卸为 MyBatis 的映射接口 */
public interface BookDao {
    /**
     * 接口办法对应 SQL 映射文件 UserMapper.xml 中的 id
     */
    public MyBook selectBookBySN(Integer sn);
    public List<MyBook> selectAllBook();
    public int addBook(MyBook book);
    public int updateBook(MyBook book);
    public int deleteBook(Integer sn);
}

com.mybatis 包下的 BookMapper.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="com.dao.BookDao">
    <!-- 依据 sn 查问书籍记录 -->
    <select id="selectBookBySN" parameterType="Integer" 
        resultType="com.po.MyBook">
        select * from book where sn=#{sn}
    </select>
    <!-- 查问所有书籍信息 -->
    <select id="selectAllBook"  resultType="com.po.MyBook">
        select * from book
    </select>
    <!-- 增加一条书籍记录,#{bookName} 为 com.po.MyBook 的属性值 -->
    <insert id="addBook" parameterType="com.po.MyBook">
        insert into book (bookName,bookPrice) values(#{bookName},#{bookPrice})
    </insert>
    <!-- 批改一条书籍记录 -->
    <update id="updateBook" parameterType="com.po.MyBook">
        update book set bookName = #{bookName},bookPrice = #{bookPrice} where sn=#{sn}
    </update>
    <!-- 删除一条书籍记录 -->
    <delete id="deleteBook" parameterType="Integer"> 
        delete from book where sn=#{sn}
    </delete>
</mapper>

com.mybatis 包下的 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>
    <!-- 通知 MyBatis 到哪里去找映射文件 -->
     <mappers>
        <mapper resource="com/mybatis/BookMapper.xml"/>
     </mappers>
</configuration>

com.mybatis.mapper 包下的 BookMapper.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="com.dao.UserDao">
    <!-- 依据 sn 查问书籍记录 -->
    <select id="selectBookBySN" parameterType="Integer" 
        resultType="com.po.MyBook">
        select * from book where sn = #{sn}
    </select>
    <!-- 查问所有书籍信息 -->
    <select id="selectAllBook"  resultType="com.po.MyBook">
        select * from book
    </select>
    <!-- 增加一条书籍记录,#{bookName} 为 com.po.MyBook 的属性值 -->
    <insert id="addBook" parameterType="com.po.MyBook">
        insert into book (bookName,bookPrice) values(#{bookName},#{bookPrice})
    </insert>
    <!-- 批改一条书籍记录 -->
    <update id="updateBook" parameterType="com.po.MyBook">
        update book set bookName = #{bookName},bookPrice = #{bookPrice} where sn = #{sn}
    </update>
    <!-- 删除一条书籍记录 -->
    <delete id="deleteBook" parameterType="Integer"> 
        delete from user where sn = #{sn}
    </delete>
</mapper>

com.mybatis.po 包下的 MyBook.java

package com.mybatis.po;
/**
 *springtest 数据库中 book 表的长久化类
 */
public class MyBook {
    private Integer sn;// 主键
    private String bookName;
    private Float  bookPrice;
    public Integer getSn() {return sn;}
    public void setSn(Integer sn) {this.sn = sn;}
    public String getBookName() {return bookName;}
    public void setBookName(String bookName) {this.bookName = bookName;}
    public Float getBookPrice() {return bookPrice;}
    public void setBookPrice(Float bookPrice) {this.bookPrice = bookPrice;}
    @Override
    public String toString() {return "MyBook [sn=" + sn + ", bookName=" + bookName + ", bookPrice=" + bookPrice + "]";
    }
}

com.mybatis.test 包下的 MyBatisTest.java

package com.mybatis.test;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import com.mybatis.po.MyBook;

public class MyBatisTest {public static void main(String[] args) {
        try {
            // 读取配置文件 mybatis-config.xml
            InputStream config = Resources.getResourceAsStream("mybatis-config.xml");
            // 依据配置文件构建 SqlSessionFactory
            SqlSessionFactory ssf = new SqlSessionFactoryBuilder().build(config);
            // 通过 SqlSessionFactory 创立 SqlSession
            SqlSession ss = ssf.openSession();
            //SqlSession 执行映射文件中定义的 SQL,并返回映射后果
            //com.mybatis.mapper.UserMapper.selectUserById 为 UserMapper.xml 中的命名空间 +select 的 id
            // 查问一条书籍记录
            MyBook mb = ss.selectOne("com.mybatis.mapper.BookMapper.selectBookBySN", 1);
            System.out.println(mb);
            // 增加一条书籍记录
            MyBook addmb = new MyBook();
            addmb.setSn(24);
            addmb.setBookName("三国演义");
            addmb.setBookPrice((float) 50.2);
            ss.insert("com.mybatis.mapper.BookMapper.addBook",addmb);
            // 批改一条书籍记录 
            MyBook updatemb = new MyBook();
            updatemb.setSn(1);
            updatemb.setBookName("水浒传");
            updatemb.setBookPrice((float) 40.1);
            ss.update("com.mybatis.mapper.BookMapper.updateBook", updatemb);
            // 删除一条书籍记录
            ss.delete("com.mybatis.mapper.BookMapper.deleteBook", 3);
            // 查问所有书籍记录
            List<MyBook> listMb = ss.selectList("com.mybatis.mapper.BookMapper.selectAllBook");
            for (MyBook myBook : listMb) {System.out.println(myBook);
            }
            // 提交事务
            ss.commit();
            // 敞开 SqlSession
            ss.close();} catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();}
    }
}

com.po 包下的 MyBook.java

package com.po;
/**
 *springtest 数据库中 book 表的长久化类
 */
public class MyBook {
    private Integer sn;// 主键
    private String bookName;
    private Float  bookPrice;
    
    public Integer getSn() {return sn;}
    public void setSn(Integer sn) {this.sn = sn;}
    public String getBookName() {return bookName;}
    public void setBookName(String bookName) {this.bookName = bookName;}
    public Float getBookPrice() {return bookPrice;}
    public void setBookPrice(Float bookPrice) {this.bookPrice = bookPrice;}
    
    @Override
    public String toString() {return "MyBook [sn=" + sn + ", bookName=" + bookName + ", bookPrice=" + bookPrice + "]";
    }
}

applicationContext.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:tx="http://www.springframework.org/schema/tx" 
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd">
    <!-- 指定须要扫描的包(包含子包),使注解失效 -->
    <context:component-scan base-package="com.dao"/>
    <context:component-scan base-package="com.controller"/>
    <!-- 配置数据源 -->
    <bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource">
            <property name="driverClassName" value="com.mysql.jdbc.Driver" />
            <property name="url" value="jdbc:mysql://localhost:3306/springtest?characterEncoding=utf8&amp;useSSL=false"/>
            <property name="username" value="root" />
            <property name="password" value="123456" />
            <!-- 最大连接数 -->
            <property name="maxTotal" value="30"/>
            <!-- 最大闲暇连接数 -->
            <property name="maxIdle" value="10"/>
            <!-- 初始化连接数 -->
            <property name="initialSize" value="5"/>
    </bean>
    <!-- 增加事务反对 -->
    <bean id="txManager"   
        class="org.springframework.jdbc.datasource.DataSourceTransactionManager">   
        <property name="dataSource" ref="dataSource" />   
    </bean> 
    <!-- 开启事务注解 -->
    <tx:annotation-driven transaction-manager="txManager" />
     <!-- 配置 MyBatis 工厂,同时指定数据源,并与 MyBatis 完满整合 -->  
     <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">  
        <property name="dataSource" ref="dataSource" />  
        <!-- configLocation 的属性值为 MyBatis 的外围配置文件 -->
        <property name="configLocation" value="classpath:com/mybatis/mybatis-config.xml"/>
    </bean>  
    <!--Mapper 代理开发,应用 Spring 主动扫描 MyBatis 的接口并拆卸(Spring 将指定包中所有被 @Mapper 注解标注的接口主动拆卸为 MyBatis 的映射接口)--> 
     <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
         <!-- mybatis-spring 组件的扫描器 -->
         <property name="basePackage" value="com.dao"/>
         <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
     </bean>
</beans>

log4j.properties

# Global logging configuration
log4j.rootLogger=ERROR, stdout
# MyBatis logging configuration...
log4j.logger.com.dao=DEBUG
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

正文完
 0