tags: Mybatis


Mybatis and Spring integration

Now that we have learned the basic development of Mybatis, it is time to integrate Mybatis with Spring!

The Oracle database is used for the following tests

Import the jar package

  • aopalliance.jar
  • Asm – 3.3.1. Jar
  • aspectjweaver.jar
  • C3p0-0.9.1.2. Jar
  • Additional – 2.2.2. Jar
  • commons-logging.jar
  • Log4j – 1.2.16. Jar
  • Mybatis 3.1.1 -. The jar
  • Mybatis – spring – 1.1.1. The jar
  • Mysql connector – Java – 5.1.7 – bin. The jar
  • ojdbc5.jar
  • Org. Springframework. Aop – 3.0.5. RELEASE. The jar
  • Org. Springframework. Asm – 3.0.5. RELEASE. The jar
  • Org. Springframework. Beans – 3.0.5. RELEASE. The jar
  • Org. Springframework. The context – 3.0.5. RELEASE. The jar
  • Org. Springframework. Core – 3.0.5. RELEASE. The jar
  • Org. Springframework. Expression – 3.0.5. RELEASE. The jar
  • Org. Springframework. JDBC – 3.0.5. RELEASE. The jar
  • Org. Springframework. Orm – 3.0.5. RELEASE. The jar
  • Org. Springframework. Transaction – 3.0.5. RELEASE. The jar
  • Org. Springframework. Web. Servlet – 3.0.5. The jar
  • Org. Springframework. Web – 3.0.5. RELEASE. The jar

Create a table


create table emps(
  eid number(5) primary key,
  ename varchar2(20),
  esal number(8.2),
  esex varchar2(2));Copy the code

Create the entity


package entity;

/** * Employee *@author AdminTC
 */
public class Emp {
	private Integer id;
	private String name;
	private Double sal;
	private String sex;
	public Emp(a){}
	public Emp(Integer id, String name, Double sal, String sex) {
		this.id = id;
		this.name = name;
		this.sal = sal;
		this.sex = sex;
	}
	public Integer getId(a) {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getName(a) {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Double getSal(a) {
		return sal;
	}
	public void setSal(Double sal) {
		this.sal = sal;
	}
	public String getSex(a) {
		return sex;
	}
	public void setSex(String sex) {
		this.sex = sex; }}Copy the code

Create a mapping file between entities and tables


<?xml version="1.0" encoding="UTF-8" ? >

      

<mapper namespace="empNamespace">
	
	<resultMap type="entity.Emp" id="empMap">
		<id property="id" column="eid"/>
		<result property="name" column="ename"/>
		<result property="sal" column="esal"/>
		<result property="sex" column="esex"/>
	</resultMap>	
	
	<! -- Add staff -->
	<insert id="add" parameterType="entity.Emp">
		insert into emps(eid,ename,esal,esex) values(#{id},#{name},#{sal},#{sex})
	</insert>
	
</mapper>
Copy the code

Create Mybatis mapping file configuration environment

The database information is managed by Spring! Mybatis configuration file is responsible for loading the corresponding mapping file


	<mappers>
		<mapper resource="zhongfucheng/entity/EmpMapper.xml"/>

	</mappers>
</configuration>
Copy the code

Configure the Spring core filter.


    <! Core SpringMVC Core Controller -->
    <servlet>
        <servlet-name>DispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring.xml</param-value>
        </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>DispatcherServlet</servlet-name>
        <url-pattern>*.action</url-pattern>
    </servlet-mapping>

Copy the code

Configure database information and transactions


<?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:tx="http://www.springframework.org/schema/tx"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">


    <! C3P0 connection pool -->
    <bean id="comboPooledDataSourceID" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="oracle.jdbc.driver.OracleDriver"/>
        <property name="jdbcUrl" value="JDBC: oracle: thin: @ 127.0.0.1:1521: ZHONGFUCHENG"/>
        <property name="user" value="scott"/>
        <property name="password" value="tiger"/>
    </bean>


    <! SqlSessionFactoryBean = SqlSessionFactoryBean
    <bean id="sqlSessionFactoryBeanID" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="configLocation" value="classpath:mybatis.xml"/>
        <property name="dataSource" ref="comboPooledDataSourceID"/>
    </bean>


    <! Mybatis transaction manager = Mybatis transaction manager = Mybatis transaction manager
    <bean id="dataSourceTransactionManagerID" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="comboPooledDataSourceID"/>
    </bean>

    <! -- Configure transaction notification, i.e. which methods need transaction support -->
    <tx:advice id="tx" transaction-manager="dataSourceTransactionManagerID">
        <tx:attributes>
            <tx:method name="*" propagation="REQUIRED"/>
        </tx:attributes>
    </tx:advice>

    <! Configure the transaction aspect, i.e., which classes under the package need transactions -->
    <aop:config>
        <aop:pointcut id="pointcut" expression="execution(* zhongfucheng.service.*.*(..) )"/>
        <aop:advisor advice-ref="tx" pointcut-ref="pointcut"/>
    </aop:config>

    <! -- Scan annotations -->
    <context:component-scan base-package="zhongfucheng"/>


</beans>

Copy the code

Create Dao, Service, and Action


@Repository
public class EmpDao {
    @Autowired
    private SqlSessionFactory sqlSessionFactory;
    /** * add staff */
    public void add(Emp emp) throws Exception {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        sqlSession.insert("empNamespace.add", emp); sqlSession.close(); }}Copy the code
@Service
public class EmpService {


    @Autowired
    private zhongfucheng.dao.EmpDao empDao;
    public void addEmp(Emp emp) throws Exception { empDao.add(emp); }}Copy the code

@Controller
@RequestMapping("/emp")
public class EmpAction {

    @Autowired
    private EmpService empService;

    @RequestMapping("/register")
    public void register(Emp emp) throws Exception {
        empService.addEmp(emp);
        System.out.println("Registration successful"); }}Copy the code

JSP page test


<% @ page language="java" pageEncoding="UTF-8"% >

      
<html>
  <head>
    <title>Employee registration</title>
  </head>
  <body>
	<form action="${pageContext.request.contextPath}/emp/register.action" method="POST">
		<table border="2" align="center">
			<tr>
				<th>Serial number</th>
				<td><input type="text" name="id"></td>
			</tr>
			<tr>
				<th>The name</th>
				<td><input type="text" name="name"></td>
			</tr>
			<tr>
				<th>salary</th>
				<td><input type="text" name="sal"></td>
			</tr>
			<tr>
				<th>gender</th>
				<td>
					<input type="radio" name="sex" value="Male"/>male<input type="radio" name="sex" value="Female" checked/>female</td>
			</tr>
			<tr>
				<td colspan="2" align="center">
					<input type="submit" value="Registered"/>
				</td>
			</tr>
		</table>
	</form>		
  </body>
</html>

Copy the code

conclusion

  • Web.xml loads the Spring configuration file
  • The Spring configuration file configures the data connection pool, SessionFactory, transaction, and scan annotations
  • Mybatis general configuration file, entity and corresponding mapping file
  • Add the mapping file to the total configuration file.

If you find this article helpful, give the author a little encouragement