Springmvc+mybatis configuration process and examples

Recently, the company wants to make a universal remote control, which can be remotely controlled to the universal remote control through the mobile phone APP, and finally the universal remote control
can Part of it is inseparable from the development of the cloud. At present, the company has no background personnel, and I am doing Android development. Our company is a small company. As far as the current project is concerned, through my evaluation, the cost of recruiting relevant personnel to develop is still quite high, so the company is If you are unwilling to recruit background personnel, what should you do? I will do it, who told me that I am omnipotent, don't laugh, I also did background development, but I used to be a handyman!
Stop talking, back to the topic. All software development processes are roughly as follows:
First: configuration
Second : demo
Third: actual combat

Well,
the first step is to configure springmvc+mybatis
1. Import jar, import all jar packages related to springMVC and mybatis
2. Create spring configuration file 3.
Configure data source
4. Create sqlsessionFactory
5. Configure transaction
6. Configure transaction propagation 7.
Configure aop
8. Configure mapping mapper
9. Configure automatic scanning

Relevant demos and screenshots
1. Import jar, import all jar packages related to springMVC and mybatis
Write picture description here
2. Create spring configuration files Create spring configuration files of beans.xml and jdbc.properties database configuration files
in source code directory
Among them, the configuration of jdbc.properties The demo is as follows:

driverClass=com.mysql.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/employee
username=psc
password=powerstronic

3. Configure the data source
In the beans.xml file, add the data source

<!-- 将属性资源文件加载到Spring的上下文中 -->
    <bean class="org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer">
        <property name="locations">
            <list>
                <value>classpath:jdbc.properties</value>
            </list>
        </property>
    </bean>
    <!-- 配置数据源 -->
       <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"> 
              <property name="driverClassName" value="${driverClass}"/> 
               <property name="url" value="${url}"/> 
               <property name="username" value="${username}"/> 
               <property name="password" value="${password}"/>  
       </bean> 

4. Create sqlsessionFactory

  <bean id="sqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">
       <!-- 指定数据源 -->
         <property name="dataSource" ref="dataSource"/> 
         <!-- 指定mybatis的配置文件 -->
         <property name="configLocation" value="classpath:MyBatis-config.xml"/> 
       </bean>

Among them, the code of MyBatis-config.xml is as follows:

<?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>
    <typeAliases>
        <typeAlias type="com.psc.mrkong.user.User" alias="user"/>
    </typeAliases>

    <mappers>
        <mapper resource="com/psc/mrkong/mapper/User.xml"/>
    </mappers>

</configuration>

5. Configuration transaction

 <!-- 配置事务 -->
       <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
         <property name="dataSource" ref="dataSource"/> 
       </bean>

6. Configure transaction propagation

 <!-- 指定事务的传播特性 -->
        <tx:advice id="txAdvice" transaction-manager="transactionManager">
         <tx:attributes>
            <tx:method name="find*" read-only="true"/>
            <tx:method name="get*" read-only="true"/>
            <tx:method name="query*" read-only="true"/>
            <tx:method name="add*"  propagation="REQUIRED"/>
            <tx:method name="put*"  propagation="REQUIRED"/>
            <tx:method name="update*"  propagation="REQUIRED"/>
            <tx:method name="change*"  propagation="REQUIRED"/>
            <tx:method name="del*"  propagation="REQUIRED"/>
         </tx:attributes>
       </tx:advice>

7. configure aop

  <!-- 配置aop -->
       <aop:config>
            <aop:pointcut expression="execution(* com.psc.mrkong.service..*.*(..))" id="pointcut"/>
            <aop:advisor advice-ref="txAdvice" pointcut-ref="pointcut"/>
       </aop:config>

8. Configure mapping mapper

  <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
            <property name="basePackage" value="com.psc.mrkong.mapper"></property>
       </bean>

9. To configure automatic scanning, add the following configuration under the first line of sub-nodes under beans.xml

OK, so far, we have completed the basic configuration of springMVC and mybatis, and then we will write a test demo, which is
the second demo
1. Complete the most basic test and create a class containing the main function for testing Obtain the sqlSessionFactoryBean object, and then print it out. The running effect can normally print out the sqlSessionFactory object.
The demo is as follows:

package com.psc.test;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.psc.mrkong.service.UserService;

public class MainTest {

    public static void main(String[] args) {
         ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
         SqlSessionFactory sqlSessionFactory=(SqlSessionFactory) context.getBean("sqlSessionFactoryBean");
         System.out.println(sqlSessionFactory);
    }
}

2. Test the connection to the database and insert a record

  • Create a User bean class
package com.psc.mrkong.po;

public class User {

    private int sid;
    private String ename;

    private int eage;
    public String getEname() {
        return ename;
    }
    public void setEname(String ename) {
        this.ename = ename;
    }
    public int getEage() {
        return eage;
    }
    public void setEage(int eage) {
        this.eage = eage;
    }
    public int getSid() {
        return sid;
    }
    public void setSid(int sid) {
        this.sid = sid;
    }
}
  • Create mapper interface UserMapper
package com.psc.mrkong.mapper;

import com.psc.mrkong.po.User;

public interface UserMapper {

    int addUser(User user);
}
  • Create mapper's sql mapping configuration file User.xml to realize sql insert record function
<?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.psc.mrkong.mapper.UserMapper">
    <insert id="addUser" parameterType="user">
    insert into emp ( ename,age) values ( #{ename},#{eage})
    </insert>
</mapper>
  • Create service interface and implementation class

service interfaceUserService

package com.psc.mrkong.service;

import com.psc.mrkong.po.User;

public interface UserService {

    boolean addUser(User user);
}

service interface implementation class

package com.psc.mrkong.service.impl;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.psc.mrkong.mapper.UserMapper;
import com.psc.mrkong.po.User;
import com.psc.mrkong.service.UserService;


public class UserServiceImpl implements UserService{
    
    

    UserMapper userMapper;
    @Override
    public boolean addUser(User user) {
        int add = userMapper.addUser(user);
        return add>0;
    }

}
  • Annotate to get the mapper interface and its implementation
package com.psc.mrkong.service.impl;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.psc.mrkong.mapper.UserMapper;
import com.psc.mrkong.po.User;
import com.psc.mrkong.service.UserService;
//注解注册service
@Service
public class UserServiceImpl implements UserService{
    
    
    //注解获取mapper实现
    @Resource(name="userMapper")
    UserMapper userMapper;
    @Override
    public boolean addUser(User user) {
        int add = userMapper.addUser(user);
        return add>0;
    }

}
  • main function test demo
package com.psc.test;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.psc.mrkong.service.UserService;

public class MainTest {

    public static void main(String[] args) {
         ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
         UserService userService=(UserService) context.getBean("userServiceImpl");
         User user=new User();
         user.setEname("大亨");
         user.setEage(30);
         System.out.println(userService.addUser(user));
    }

}

Running effect: successfully add a record to the database

Third, actual combat
In fact , actual combat is the operation of adding, deleting, modifying and checking the database on springMVC+mybatis, basically refer to the second step to achieve

click to download

Guess you like

Origin blog.csdn.net/huangxuanheng/article/details/78447239