一.导包
1.Mybatis的核心包以及依赖包
2.Spring的jar包(这个可能麻烦点)
3.mybastis和spring整合包
4.数据库驱动包
5.根据自己需求,junit,jstl等jar包导入,下面也将springmvc所需的jar也导入了
二.设计表,创建表
三.创建mybatis和spring的主配置文件
1.书写mybatis配置。由于数据库连接的参数交给spring保管,只配别名和引入映射文件就够了
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis/dtd/mybatis-3-config.dtd"> <configuration> <typeAliases> <package name="cn.itheima.pojo"/> </typeAliases> <mappers> <mapper resource="cn/itheima/dao/UserMapper.xml"/> </mappers> </configuration>
2.书写spring配置文件。依次配置连接池,session工厂,配置dao(这里采用原先的dao开发方式)
<!-- 读取数据库信息配置文件 --> <context:property-placeholder location="classpath:db.properties"/> <!-- 配置连接池 --> <bean name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="jdbcUrl" value="${jdbc.jdbcUrl}" ></property> <property name="driverClass" value="${jdbc.driverClass}" ></property> <property name="user" value="${jdbc.user}" ></property> <property name="password" value="${jdbc.password}" ></property> </bean> <!-- 配置工厂 --> <bean name="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <!-- 连接池 --> <property name="dataSource" ref="dataSource"></property> <!-- mybatis主配置信息 --> <property name="configLocation" value="classpath:sqlMapConfig.xml"></property> </bean> <!-- 配置dao --> <bean name="userDao" class="cn.itheima.dao.impl.UserDaoImpl"> <property name="sqlSessionFactory" ref="sqlSessionFactory"></property> </bean>
3.创建实体类
public class User implements Serializable{ private Integer user_id; private String user_name; public Integer getUser_id() { return user_id; } public void setUser_id(Integer user_id) { this.user_id = user_id; } public String getUser_name() { return user_name; } public void setUser_name(String user_name) { this.user_name = user_name; } @Override public String toString() { return "User [user_id=" + user_id + ", user_name=" + user_name + "]"; } }
4.创建dao接口和dao实现类
public interface UserDao { public List<User> findUserList(); }
public class UserDaoImpl extends SqlSessionDaoSupport implements UserDao { public List<User> findUserList() { //通过继承sqlSessionDaoSupprot,调用getSqlSession获得session SqlSession session = super.getSqlSession(); List<User> list = session.selectList("test.findUserList"); return list; } }
5.创建映射文件userMapper.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis/dtd/mybatis-3-mapper.dtd"> <mapper namespace="test"> <select id="findUserList" resultType="User"> select * from user2 </select> </mapper>
6.书写测试类
public class Junit { @Test public void fun1() { ApplicationContext ac = new ClassPathXmlApplicationContext("classpath:applicationContext.xml"); UserDao dao = (UserDao) ac.getBean("userDao"); List<User> list = dao.findUserList(); System.out.println(list); } }
原文:https://www.cnblogs.com/ibcdwx/p/12943537.html