Requirements and process analysis

demand

Add, delete, modify, and query the Account table using the SSM framework.

Step analysis

Prepare database and table records 2. Create web project 3. Write Mybatis in SSM environment can be used alone 4. 5. Spring integration mybatis 6. Writing springMVC can be used alone in an SSM environment 7. Spring integrates springMVCCopy the code

Environment set up

1) Prepare database and table records

CREATE TABLE `account` (
    `id` int(11) NOT NULL AUTO_INCREMENT,
    `name` varchar(32) DEFAULT NULL.`money` double DEFAULT NULL,
    PRIMARY KEY (`id`))ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;

insert into `account`(`id`.`name`.`money`) values (1.'tom'.1000), (2.'jerry'.1000);
Copy the code

2) Create a Web project

Writing Mybatis can be used alone in the SSM environment

Requirements: Based on Mybatis first to achieve the account table query

1) Relevant coordinates

<! - mybatis coordinates - >
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.47</version>
</dependency>
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.1.15</version>
</dependency>
<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>3.5.1 track of</version>
</dependency>
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
</dependency>
Copy the code

2) Account entity

public class Account {

    private Integer id;
    private String name;
    private Double money;
}
Copy the code

3) AccountDao interface

public interface AccountDao {

    public List<Account> findAll(a);
}
Copy the code

4) AccountDao.xml mapping


      
<! DOCTYPEmapper PUBLIC "- / / mybatis.org//DTD Mapper / 3.0 / EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.lagou.dao.AccountDao">
    <select id="findAll" resultType="Account">
        select * from account
    </select>
</mapper>
Copy the code

5) MyBatis core configuration file

jdbc.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/spring_db
jdbc.username=root
jdbc.password=root
Copy the code

SqlMapConfig.xml


      
<! DOCTYPEconfiguration PUBLIC "- / / mybatis.org//DTD Config / 3.0 / EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>

    <! - loading properties - >
    <properties resource="jdbc.properties"/>

    <! -- Type alias configuration -->
    <typeAliases>
        <package name="com.lagou.domain"/>
    </typeAliases>

    <! -- Environment Configuration -->
    <environments default="mysql">
        <! -- Use MySQL -->
        <environment id="mysql">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="${jdbc.driver}"/>
                <property name="url" value="${jdbc.url}"/>
                <property name="username" value="${jdbc.username}"/>
                <property name="password" value="${jdbc.password}"/>
            </dataSource>
        </environment>
    </environments>

    <! -- Load mapping -->
    <mappers>
        <package name="com.lagou.dao"/>
    </mappers>

</configuration>
Copy the code

6) Test code

public class MyBatisTest {

    @Test
    public void testMybatis(a) throws Exception {
        // Load the core configuration file
        InputStream is = Resources.getResourceAsStream("SqlMapConfig.xml");
        // Get the SQLSession factory object
        SqlSessionFactory sqlSessionFactory = new
        SqlSessionFactoryBuilder().build(is);
        // Get the SQLSession session object
        SqlSession sqlSession = sqlSessionFactory.openSession();
        // Get the Mapper proxy object
        AccountDao accountDao = sqlSession.getMapper(AccountDao.class);
        / / execution
        List<Account> list = accountDao.findAll();
        for (Account account : list) {
            System.out.println(account);
        }
        // Release resourcessqlSession.close(); }}Copy the code

Writing Spring can be used independently in an SSM environment

1) Relevant coordinates

<! - spring coordinates -- -- >
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>5.1.5. RELEASE</version>
</dependency>
<dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjweaver</artifactId>
    <version>1.8.13</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
    <version>5.1.5. RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-tx</artifactId>
    <version>5.1.5. RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-test</artifactId>
    <version>5.1.5. RELEASE</version>
</dependency>
Copy the code

2) AccountService interface

public interface AccountService {

    public List<Account> findAll(a);
}
Copy the code

3) Implementation of AccountServiceImpl

@Service
public class AccountServiceImpl implements AccountService {

    @Override
    public List<Account> findAll(a) {
        System.out.println("FindAll executed....");
        return null; }}Copy the code

4) Spring core configuration file

applicationContext.xml


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

    <! -- Annotation component scan -->
    <context:component-scan base-package="com.lagou.service"/>

</beans>
Copy the code

5) Test code

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class SpringTest {

    @Autowired
    private AccountService accountService;

    @Test
    public void testSpring(a) throws Exception { List<Account> list = accountService.findAll(); System.out.println(list); }}Copy the code

Spring integration mybatis

1) Integrate your thoughts

By delegating the creation of the MyBatis interface proxy object to Spring, we can inject dao’s proxy object into service, and then complete the integration of Spring and MyBatis.

2) Import the integration package

<! -- Mybatis integrate spring coordinates -->
<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis-spring</artifactId>
    <version>1.3.1</version>
</dependency>
Copy the code

3) Spring configuration file management mybatis

Note: The MyBatis master profile can be deleted at this point.


      
<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"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.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">
    <! -- Annotation component scan -->
    <context:component-scan base-package="com.lagou.service"/>

    <! - spring integration mybatis -- -- >
    <context:property-placeholder location="classpath:jdbc.properties"/>

    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="${jdbc.driver}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
    </bean>

    <! --SqlSessionFactory create IOC container to Spring -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <! -- Database environment configuration -->
        <property name="dataSource" ref="dataSource"/>
        <! -- Type alias configuration -->
        <property name="typeAliasesPackage" value="com.lagou.domain"/>
        <! If you want to import mybatis master configuration file, you can do the following:
        <! --<property name="configLocation" value="classpath:SqlMapConfig.xml"/>-->
    </bean>

    <! -- Map interface scan configuration, spring creates proxy object, hand it to IOC container -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.lagou.dao"/>
    </bean>
</beans>
Copy the code

4) Modify AccountServiceImpl

@Service
public class AccountServiceImpl implements AccountService {

    @Autowired
    private AccountDao accountDao;

    @Override
    public List<Account> findAll(a) {
        returnaccountDao.findAll(); }}Copy the code

Writing springMVC can be used independently in an SSM environment

Requirement: Access the method in controller to query all accounts, and jump to list.jsp page to display the list

1) Relevant coordinates

<! - for springMVC coordinates - >
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>5.1.5. RELEASE</version>
</dependency>
<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>3.1.0</version>
    <scope>provided</scope>
</dependency>
<dependency>
    <groupId>javax.servlet.jsp</groupId>
    <artifactId>jsp-api</artifactId>
    <version>2.2</version>
    <scope>provided</scope>
</dependency>
<dependency>
    <groupId>jstl</groupId>
    <artifactId>jstl</artifactId>
    <version>1.2</version>
</dependency>
Copy the code

2) Import page resources

3) Front-end controller DispathcerServlet


      
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">

    <! -- Front-end 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-mvc.xml</param-value>
        </init-param>
        <load-on-startup>2</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>DispatcherServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <! -- Post -->
    <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>
    </filter>
    <filter-mapping>
        <filter-name>CharacterEncodingFilter</filter-name>
        <url-pattern>/ *</url-pattern>
    </filter-mapping>
</web-app>
Copy the code

4) AccountController and list.jsp

@Controller
@RequestMapping("/account")
public class AccountController {

    @RequestMapping("/findAll")
    public String findAll(Model model) {
        List<Account> list = new ArrayList<>();
        list.add(new Account(1."Zhang".1000d));
        list.add(new Account(2."Bill".1000d));
        model.addAttribute("list", list);
        return "list"; }}Copy the code
<c:forEach items="${list}" var="account">
    <tr>
        <td>
            <input type="checkbox" name="ids">
        </td>
        <td>${account.id}</td>
        <td>${account.name}</td>
        <td>${account.money}</td>
        <td>
            <a class="btn btn-default btn-sm" href="update.jsp"</a> <aclass="btn btn-default btn-sm" href=""</a> </td> </tr> </c:Copy the code

5) springMVC core configuration file

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <! -- Component scan -->
    <context:component-scan base-package="com.lagou.controller"/>

    <! -- MVC annotation enhancement -->
    <mvc:annotation-driven/>

    <! -- View resolver -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/"/>
        <property name="suffix" value=".jsp"/>
    </bean>

    <! Static resource mapping -->
    <mvc:default-servlet-handler/>
</beans>
Copy the code

Spring integration for springMVC

1) Integrate your thoughts

Spring and Spring MVC don’t have to be integrated at all, they’re just one.

However, we need to integrate Spring with the Web container so that the Spring configuration file is automatically loaded when the Web container is started and the Spring IOC container is destroyed when the Web container is destroyed.

2) Spring and Web container integration

The ContextLoaderListener listener in the Spring-Web package can be used to create or destroy the IOC container at the same time by listening for the creation and destruction of the servletContext container.

<! Spring with web container integration -->
<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>
Copy the code

3) Modify the AccountController

@Controller
@RequestMapping("/account")
public class AccountController {

    @Autowired
    private AccountService accountService;

    @RequestMapping("/findAll")
    public String findAll(Model model) {

        List<Account> list = accountService.findAll();
        model.addAttribute("list", list);
        return "list"; }}Copy the code

Spring configures declarative transactions

1) Add declarative transactions to spring configuration files

<! -- Transaction manager -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <property name="dataSource" ref="dataSource"></property>
</bean>
<! -- Enable transaction annotation support -->
<tx:annotation-driven/>
Copy the code
@Service
@Transactional
public class AccountServiceImpl implements AccountService {}Copy the code

2) add a JSP

<form action="${pageContext.request.contextPath}/account/save" method="post">
    <div class="form-group">
        <label for="name">Name:</label>
        <input type="text" class="form-control" id="name" name="name"
        placeholder="Please enter your name">
    </div>
    <div class="form-group">
        <label for="age">Balance:</label>
        <input type="text" class="form-control" id="age" name="age"
        placeholder="Please enter the balance">
    </div>

    <div class="form-group" style="text-align: center">
        <input class="btn btn-primary" type="submit" value="Submit" />
        <input class="btn btn-default" type="reset" value="Reset" />
        <input class="btn btn-default" type="button" onclick="history.go(-1)" value="Return" />
    </div>
</form>
Copy the code

3) the AccountController

@RequestMapping("/save")
public String save(Account account){
    accountService.save(account);
    return "redirect:/account/findAll";
}
Copy the code

4) AccountService interface and implementation class

public void save(Account account);
Copy the code
@Service
@Transactional
public class AccountServiceImpl implements AccountService {

    @Override
    public void save(Account account) { accountDao.save(account); }}Copy the code

5) AccountDao

void save(Account account);
Copy the code

6) AccountDao.xml mapping

<insert id="save" parameterType="Account">
    insert into account (name, money) values (#{name}, #{money})
</insert>
Copy the code

Modify the operating

The echo data

1 the AccountController

@RequestMapping("/findById")
public String findById(Integer id, Model model) {
    Account account = accountService.findById(id);
    model.addAttribute("account", account);
    return "update";
}
Copy the code

② AccountService interface and implementation class

Account findById(Integer id);
Copy the code
@Override
public Account findById(Integer id) {
    return accountDao.findById(id);
}
Copy the code

③ The AccountDao interface and mapping file

Account findById(Integer id);
Copy the code
<select id="findById" parameterType="int" resultType="Account">
    select * from account where id = #{id}
</select>
Copy the code

(4) the update. The JSP

<form action="${pageContext.request.contextPath}/account/update" method="post">
    <input type="hidden" name="id" value="${account.id}">
    <div class="form-group">
        <label for="name">Name:</label>
        <input type="text" class="form-control" id="name" name="name" value="${account.name}" placeholder="Please enter your name">
    </div>
    <div class="form-group">
        <label for="money">Balance:</label>
        <input type="text" class="form-control" id="money" name="money" value="${account.money}" placeholder="Please enter the balance">
    </div>

    <div class="form-group" style="text-align: center">
        <input class="btn btn-primary" type="submit" value="Submit" />
        <input class="btn btn-default" type="reset" value="Reset" />
        <input class="btn btn-default" type="button" onclick="history.go(-1)" value="Return" />
    </div>
</form>
Copy the code

Account updates

1 the AccountController

@RequestMapping("/update")
public String update(Account account){
    accountService.update(account);
    return "redirect:/account/findAll";
}
Copy the code

② AccountService interface and implementation class

void update(Account account);
Copy the code
@Override
public void update(Account account) {
    accountDao.update(account);
}
Copy the code

③ The AccountDao interface and mapping file

void update(Account account);
Copy the code
<update id="update" parameterType="Account">
    update account set name = #{name},money = #{money} where id = #{id}
</update>
Copy the code

Batch delete

1) list. The JSP

<script>
    $('#checkAll').click(function () {$('input[name="ids"]').prop('checked', $(this).prop('checked')); $(})'#deleteBatchBtn').click(function () {
        if (confirm('Are you sure you want to delete it? ')) {
            if ($('input[name="ids"]:checked').length > 0) {$('#deleteBatchForm').submit();
            } else {
                alert('What are you thinking? ')}}})</script>
Copy the code

2) the AccountController

@RequestMapping("/deleteBatch")
public String deleteBatch(Integer[] ids) {
    accountService.deleteBatch(ids);
    return "redirect:/account/findAll";
}
Copy the code

3) AccountService interface and implementation class

void deleteBatch(Integer[] ids);
Copy the code
@Override
public void deleteBatch(Integer[] ids) {
    accountDao.deleteBatch(ids);
}
Copy the code

4) AccountDao interface and mapping file

void deleteBatch(Integer[] ids);
Copy the code
<delete id="deleteBatch" parameterType="int">
    delete from account
    <where>
        <foreach collection="array" open="id in(" close=")" separator="," item="id">
            #{id}
        </foreach>
    </where>
</delete>
Copy the code