SM框架(总结整合Spring和MyBatis框架)

导入spring和MyBatis使用的jar包

 

 mybatis-spring-1.2.0.jar
下载路径:http://github.com/mybatis/spring/releases

mybatis-spring-1.3.2.jar 下载路径:mybatis-spring-1.3.2.zip-Java文档类资源-CSDN下载下载mybatis-spring-1.3.2.jar包更多下载资源、学习资料请访问CSDN下载频道.https://download.csdn.net/download/qq_56637516/33247102

添加jdbc配置文件

jdbc.driver=com.mysql.jdbc.Driver

jdbc.url=jdbc:mysql://localhost:3306/epet?useUnicode=true&characterEncoding=utf8

jdbc.username=epetadmin

jdbc.password=root

添加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><!-- 配置 -->

    <settings>
        <setting name="logImpl" value="STDOUT_LOGGING"/>
    </settings><!-- 设置 -->
    <typeAliases>
        <package name="com.bdqn.pojos"/>
    </typeAliases><!-- 类型命名 -->
    
</configuration>

添加spring-config 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"

       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.xsd">

<!--    开启注解-->
    <context:component-scan base-package="com.bdqn"></context:component-scan>
    <!--    指定引入文件地址  -->
    <context:property-placeholder location="jdbc.properties"/>
    <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="username" value="${jdbc.username}"></property>
        <property name="password" value="${jdbc.password}"/>
    </bean>

    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!--        引入数据源-->
        <property name="dataSource" ref="dataSource" />
<!--        加载mybatis配置文件-->
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
    </bean>
<!--    指定映射器加载的SQL映射文件-->
    <bean id="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!--        指定映射文件包的位置-->
        <property name="basePackage" value="com.bdqn.dao.*"/>
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
    </bean>

<!--    配置SQLSessionTemplate-->
    <bean  id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
        <constructor-arg name="sqlSessionFactory" ref="sqlSessionFactory"/>
    </bean>

</beans>

将MyBatis的核心组件由spring中IOC接管创建并进行依赖管理。

  • 构建SqlSessionFactory

创建实体类

public class Pet {

    private int id;
    private int masterId;
    private String name;
    private int typeId;
    private int health;
    private int love;
    private Timestamp adopt_time;
    private int status;
    //get set ………………
}

创建dao层及接口对应的mapper xml文件

public interface EpetDao {
    /**
     * 查询所有的宠物
     * @return
     */
    List<Pet> queryEpets();

}
<?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.bdqn.dao.epetDao.EpetDao">
<!--    查询所有的宠物-->
    <select id="queryEpets" resultType="epet">
        SELECT * FROM pet ;
    </select>
</mapper>

创建实现类

@Repository("epetDaoImpl")
public class EpetDaoImpl implements EpetDao{
    @Resource(name = "sqlSessionTemplate")
    private SqlSessionTemplate sqlSessionTemplate;

    public SqlSessionTemplate getSqlSessionTemplate() {
        return sqlSessionTemplate;
    }

    public void setSqlSessionTemplate(SqlSessionTemplate sqlSessionTemplate) {
        this.sqlSessionTemplate = sqlSessionTemplate;
    }

    /**
     * 查询所有的宠物
     * @return
     */
    @Override
    public List<Pet> queryEpets() {

        return  sqlSessionTemplate.getMapper(EpetDao.class).queryEpets();
    }
}

创建service层

@Service("epetServiceImpl")
public class EpetServiceImpl implements EpetService{
    @Resource(name = "epetDaoImpl")
    private EpetDao epetDao;

    @Override
    public List<Pet> getList() {
        return epetDao.queryEpets();
    }

    public EpetDao getEpetDao() {
        return epetDao;
    }

    public void setEpetDao(EpetDao epetDao) {
        this.epetDao = epetDao;
    }

}

创建controller层

public class PetControl extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doGet(req, resp);
    }
    
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
                ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring-config.xml");
        EpetServiceImpl ser = context.getBean("epetServiceImpl", EpetServiceImpl.class);
        List<Pet> list = ser.getList();
    }
}

测试

public class TestPet {
    public static void main(String[] args) {
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring-config.xml");
        EpetServiceImpl service = context.getBean("epetServiceImpl", EpetServiceImpl.class);
        List<Pet> list = service.getList();
        for (int i = 0; i < list.size(); i++) {
            System.out.println(list.get(i));
        }

    }
}

测试结果

Creating a new SqlSession
SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@4e268090] was not registered for synchronization because synchronization is not active
JDBC Connection [jdbc:mysql://localhost:3306/epet?useUnicode=true&characterEncoding=utf8, UserName=epetadmin@localhost, MySQL Connector Java] will not be managed by Spring
==>  Preparing: SELECT * FROM pet ;
==> Parameters: 
<==    Columns: id, master_id, name, type_id, health, love, adopt_time, status
<==        Row: 3, 1, qw, 1, 99, 55, 2021-02-02 00:00:00.0, 0
<==        Row: 4, 1, er, 1, 99, 55, 2021-02-02 00:00:00.0, 1
<==        Row: 5, 1, yt, 1, 99, 55, 2021-02-02 00:00:00.0, 1
<==        Row: 6, 1, wf, 1, 99, 55, 2021-02-02 00:00:00.0, 1
<==      Total: 4
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@4e268090]
com.bdqn.pojos.Pet@428640fa
com.bdqn.pojos.Pet@d9345cd
com.bdqn.pojos.Pet@2d710f1a
com.bdqn.pojos.Pet@29215f06

Process finished with exit code 0


版权声明:本文为qq_56637516原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。