sring引入mybatis

时间:2021-06-12 02:41:07

1、首先框架结构是这样的(jar包还是要导的)

sring引入mybatis

2、web.xml和springMVC-servlet.xml未作任何新的配置,这里简单贴一下代码:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0"> <filter>
<filter-name>characterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>characterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping> <servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/springMVC-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>/page/index.html</welcome-file>
</welcome-file-list> <!-- Spring 加载配置文件 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext*.xml</param-value>
</context-param> </web-app>
<?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:util="http://www.springframework.org/schema/util" xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-4.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd"> <!-- 使用默认的注解映射 -->
<mvc:annotation-driven /> <!-- 自动扫描controller包中的控制器 -->
<context:component-scan base-package="com.gwssi.*" /> <!-- 配置静态资源 -->
<mvc:resources location="/page/" mapping="/*" /> <!-- 视图解析器 -->
<bean id="viewReslver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/page/"></property>
<property name="suffix" value=".html"></property>
</bean>
</beans>

3、applicationContext.xml中引入mybatis

  两点:

    一  配置SqlSessionFectory 这是sqlsession的工厂,后边要通过sqlsession来执行SQL;

    二 配置映射接口,这样就会自动扫描文件中的接口进行注入。

<?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:mvc="http://www.springframework.org/schema/mvc"
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/mvc http://www.springframework.org/schema/mvc/spring-mvc-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.2.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.2.xsd"
default-autowire="byName"> <!-- <context:property-placeholder location="classpath:datasource.properties"/> -->
<!-- <context:property-placeholder properties-ref="propertyConfigurer" /> --> <!-- 加载配置文件 -->
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:*.properties</value>
</list>
</property>
</bean> <!-- 配置数据库 -->
<bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"></property>
<property name="url" value="jdbc:oracle:thin:@//127.0.0.1:1521/zpc"></property>
<property name="username" value="test"></property>
<property name="password" value="test"></property>
<property name="initialSize" value="5"></property>
</bean> <!--注入jdbcTemplate-->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"></property>
</bean> <!-- <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean" lazy-init="false">
<property name="dataSource" ref="dataSource" />
<property name="configLocation" value="classpath:hibernate.cfg.xml"></property>
<property name="mappingLocations" value="classpath:*.hbm.xml"></property>
</bean> --> <!-- 配置sqlSessionFactory, 并将数据源注入 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="configLocation" value="classpath:mybatis-config.xml" />
</bean> <!-- 配置映射接口 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.gwssi.zpc.dao" />
<!--单一数据源时可以不配制此项-->
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
</bean> <!-- 事务管理DataSourceTransactionManager -->
<!-- 配置声明式事务 -->
<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<tx:annotation-driven transaction-manager="txManager" /> <!-- 通过AOP配置提供事务增强,让service包下所有Bean的所有方法拥有事务 -->
<!-- <aop:config proxy-target-class="true">
<aop:pointcut id="serviceMethod"
expression="(execution(* com.ghc.service..*(..))) and (@annotation(org.springframework.transaction.annotation.Transactional))" />
<aop:advisor pointcut-ref="serviceMethod" advice-ref="txAdvice" />
</aop:config>
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="*" />
</tx:attributes>
</tx:advice> --> </beans>

4、mybatis-config.xml 的配置,两个功能:配置数据库信息;加载mapper文件

<?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>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC" />
<!-- 配置数据库连接信息 -->
<dataSource type="POOLED">
<property name="driver" value="oracle.jdbc.driver.OracleDriver" />
<property name="url" value="jdbc:oracle:thin:@//127.0.0.1:1521/zpc" />
<property name="username" value="test" />
<property name="password" value="test" />
</dataSource>
</environment>
</environments> <mappers>
<mapper resource="com/gwssi/zpc/dao/mybatis/userMapper.xml"/>
</mappers>
</configuration>

5、配置userMapper.xml,它是用来放SQL语句的,是所有SQL的家,用mybatis的话会有很多很多的mapper文件,要习惯。

  namespace一定要注意是dao的接口类

  resultType 用java.util.map的话就是常用的List<Map<String,Object>>,是我喜欢的东西,哈哈。

<?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.gwssi.zpc.dao.UserDao"><!-- 必须是UserDao --> <select id="information" parameterType="String" resultType="java.util.Map" > <!-- java.util.Map -->
select * from SIGN t <!-- where t.id=#{id} -->
</select> <!--根据id查询得到一个user对象-->
<select id="getUser" parameterType="String" resultType="com.gwssi.zpc.domain.User">
select * from users where id=#{id}
</select> <!-- 创建用户(Create) -->
<insert id="addUser" parameterType="com.gwssi.zpc.domain.User">
insert into users(id,name,age) values(#{id},#{name},#{age})
</insert> <!-- 删除用户(Remove) -->
<delete id="deleteUser" parameterType="String">
delete from users where id=#{id}
</delete> <!-- 修改用户(Update) -->
<update id="updateUser" parameterType="com.gwssi.zpc.domain.User">
update users set name=#{name},age=#{age} where id=#{id}
</update> <!-- 查询全部用户-->
<select id="getAllUsers" resultType="com.gwssi.zpc.domain.User">
select * from users
</select>
</mapper>

6、User.java先写一下吧

package com.gwssi.zpc.domain;

/**
*
* @author fefeishi
*
*/
public class User { private String id;
private String name;
private String age; 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 String getAge() {
return age;
} public void setAge(String age) {
this.age = age;
} }

7、然后是UserDao和UserDaoImpl

  这里注意一点dao的方法名和mapper中的id名称必须保持一致。

  这里session执行sql似乎还不是很完美,待研究。

package com.gwssi.zpc.dao;

import java.util.List;
import java.util.Map; import org.springframework.stereotype.Repository; import com.gwssi.zpc.domain.User; @Repository
public interface UserDao {//dao方法名必须和mapper中的id一致 List<Map<String, Object>> information(String id); public User getUser(String id); public void addUser(User user); public void deleteUser(String id); public void updateUser(User user); public List<User> getAllUsers();
}
package com.gwssi.zpc.dao.impl;

import java.util.List;
import java.util.Map; import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import com.gwssi.zpc.dao.UserDao;
import com.gwssi.zpc.domain.User; public class UserDaoImpl implements UserDao { @Autowired
private SqlSessionFactory sqlSessionFactory; @Override
public List<Map<String,Object>> information(String id) {
SqlSession sqlSession = sqlSessionFactory.openSession();
List<Map<String,Object>> list= sqlSession.selectOne("com.gwssi.zpc.dao.UserDao.getUser",id);
sqlSession.close();
return list;
} @Override
public User getUser(String id) {
SqlSession sqlSession = sqlSessionFactory.openSession();
User user = sqlSession.selectOne("com.gwssi.zpc.dao.UserDao.getUser",id);
sqlSession.close();
return user;
} @Override
public void addUser(User user) {
SqlSession sqlSession = sqlSessionFactory.openSession();
sqlSession.update("com.gwssi.zpc.dao.UserDao.getUser",user);
sqlSession.close();
} @Override
public void deleteUser(String id) {
SqlSession sqlSession = sqlSessionFactory.openSession();
sqlSession.update("com.gwssi.zpc.dao.UserDao.deleteUser",id);
sqlSession.close();
} @Override
public void updateUser(User user) {
SqlSession sqlSession = sqlSessionFactory.openSession();
sqlSession.selectOne("com.gwssi.zpc.dao.UserDao.updateUser",user);
sqlSession.close();
} @Override
public List<User> getAllUsers() {
SqlSession sqlSession = sqlSessionFactory.openSession();
List<User> list = sqlSession.selectList("com.gwssi.zpc.dao.UserDao.getAllUsers");
sqlSession.close();
return list;
}
}

8、contoller中简单调一下好了

package com.gwssi.zpc.controller;

import java.util.List;
import java.util.Map; import org.apache.log4j.Logger;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; import com.gwssi.zpc.dao.UserDao;
import com.gwssi.zpc.domain.User; @RestController
@RequestMapping("/a")
public class testController { @Autowired
UserDao userdao; private final static Logger log = Logger.getLogger(testController.class); @RequestMapping("/1")
public void main1(){
User user=new User();
user.setId("4");
user.setName("栾坤");
user.setAge("44");
userdao.addUser(user);
selectAll();
log.info(" ");
}
@RequestMapping("/2")
public void main2(){
User user1=new User();
user1.setId("4");
user1.setName("栾坤2");
user1.setAge("22");
userdao.updateUser(user1);
selectAll();
log.info(" ");
}
@RequestMapping("/3")
public void main3(){
userdao.deleteUser("4");
selectAll();
log.info(" ");
} @RequestMapping("/4")
public void main4(){
List<Map<String,Object>> list=userdao.information("2309685A78F1492C86DE4837F08879FD");
log.info(list.get(0).get("FILENAME"));
log.info(list.get(1).get("FILENAME"));
log.info(list.get(2).get("FILENAME"));
log.info(list.get(3).get("FILENAME"));
log.info(list.get(4).get("FILENAME"));
log.info(list.size());
} public void selectAll(){
List<User> list=userdao.getAllUsers();
for(User u:list){
log.info(u.getId()+" "+u.getName()+" "+u.getAge());
}
}
}