Myeclipse develops SpringBook integration maven+mybatis+freemarker+oracle

Keywords: Spring Attribute FreeMarker Mybatis

This article refers to two well-written blog posts.
1.http://blog.csdn.net/mmliuman/article/details/52797441
2.http://blog.didispace.com/
The second blog address contains a systematic article that can be perfectly learned from Spring boot.

Because Spring boot officially does not recommend JSP as a page engine, so I chose to be familiar with freemarker, of course, not that Spring boot can not use JSP, if you want to use JSP as a page engine, you can refer to this blog: http://blog.csdn.net/linxingliang/article/details/52017140

Because it is based on Maven for project construction and the Myclipse selected by IDE tools, plug-ins must be installed. If not, you can refer to this blog post: http://blog.csdn.net/harry_zh_wang/article/details/54803473

There are many integrated blog articles on the internet. Why do I write and build them here by myself? Because each person's development environment is different, and many original writers do not encounter problems in the actual construction process, so on the basis of referring to other Daniels, the younger brother will rebuild them and make a memo.

Right-click -> new -> other -> search for maven -> select maven project by default and select Create a simple project option.

GroupId: Company name or organization name
ArtifactId: Typically, the project project name

The generated file directory structure is as follows

Usually:
src/main/resources delegates various configuration files
src/main/java Decentralized Source Code
Test folder to drop test files
And so on

Configure jar support in pom.xml after maven project is built
The complete pom.xml is configuring its own support here, and if other jar s are needed in the project, they need to configure themselves.

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.wzh</groupId>
    <artifactId>SpringBootDemo</artifactId>
    <version>0.0.1-SNAPSHOT</version>

    <!-- Coding set -->
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>
    <!-- Spring Boot Start Parent Dependency -->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.1.RELEASE</version>
    </parent>

    <dependencies>
        <!-- Spring Boot Web rely on -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!-- Spring Boot Test rely on -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <!--View adoption freemarker Rendering -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-freemarker</artifactId>
        </dependency>

        <!-- JDBC -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>

        <!-- oracle Driven by maven I won't support it oracle Of jar Management, here I import the local warehouse, specific maven Configuration support can be Baidu -->
        <dependency>
            <groupId>com.oracle</groupId>
            <artifactId>ojdbc6</artifactId>
            <version>12.1.0.2.0</version>
        </dependency>

        <!-- mybatis -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.2.2</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.2.8</version>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.6</source>
                    <target>1.6</target>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <executions>
                    <execution>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
                <dependencies>
                    <dependency>
                        <groupId>org.springframework</groupId>
                        <artifactId>springloaded</artifactId>
                        <version>1.2.5.RELEASE</version>
                    </dependency>
                </dependencies>
            </plugin>
        </plugins>
        <!-- Specify final generation jar File name of package -->
        <finalName>springBootDemo</finalName>
    </build>
</project>

Although boot advocates convention over configuration, we still need to do a small amount of configuration.
Create the application.properties file in src/main/resources. Here is only the configuration part, which is configured according to the actual situation of the project.

## Data source configuration data source
spring.datasource.url=jdbc:oracle:thin:@localhost:1521:oracle
spring.datasource.username=system
spring.datasource.password=Password
spring.datasource.driver-class-name=oracle.jdbc.driver.OracleDriver
## Verify the validity of the connection
spring.datasource.primary.test-while-idle=true
## Validation when getting connections affects performance
spring.datasource.primary.test-on-borrow=false
## Whether to test the connection when it is returned to the connection pool
spring.datasource.primary.test-on-return=false
spring.datasource.primary.validation-query=SELECT 1 FROM DUAL
## Time interval for idle connection recovery, used with test-while-idle, set to 5 minutes
spring.datasource.primary.time-between-eviction-runs-millis=300000
## Effective time for idle connection in connection pool, set to 30 minutes
spring.datasource.primary.min-evictable-idle-time-millis=1800000
spring.datasource.primary.initial-size=5
## Specifies the maximum number of active connections in the connection pool.
spring.datasource.primary.max-active=50
## Specifies the maximum waiting time in milliseconds for the connection pool to wait for the connection to return.
spring.datasource.primary.max-wait=60000
## Specifies that the minimum value of the connection must be maintained
spring.datasource.primary.min-idle=5


# FREEMARKER (FreeMarkerAutoConfiguration)
spring.freemarker.allow-request-override=false
spring.freemarker.allow-session-override=false
spring.freemarker.cache=true
spring.freemarker.charset=UTF-8
spring.freemarker.check-template-location=true
spring.freemarker.content-type=text/html
spring.freemarker.enabled=true
spring.freemarker.expose-request-attributes=false
spring.freemarker.expose-session-attributes=false
spring.freemarker.expose-spring-macro-helpers=true
spring.freemarker.prefer-file-system-access=true
spring.freemarker.suffix=.ftl
spring.freemarker.template-loader-path=classpath:/templates/
spring.freemarker.settings.template_update_delay=0
spring.freemarker.settings.default_encoding=UTF-8
spring.freemarker.settings.classic_compatible=true
spring.freemarker.order=1

Create Program Entry Application.java

package com.wzh.application;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.apache.ibatis.io.VFS;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.tomcat.jdbc.pool.DataSource;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;

/**
 * Spring Boot Application Startup Class
 */
@SpringBootApplication // Identifying Spring Boot applications
@ComponentScan(basePackages = { "com.wzh"}) // Specify the spring management path, which is the path for those bean annotations
@MapperScan({ "com.wzh.**.mapper" }) // The mapper interface class scans the package configuration with two * directory wildcards
public class Application {

    // Program Startup Entry
    public static void main(String[] args) {
        // Start embedded Tomcat and initialize Spring environment and its Spring components
        SpringApplication.run(Application.class, args);
    }

    // Create the data source, because mybatis-spring 1.2 cancels the automatic injection of the data source, so you need to configure it manually.
    @Bean
    @ConfigurationProperties(prefix = "spring.datasource")// Specify the prefix of the data source, specified in the application.properties file
    public DataSource dataSource() {
        return new DataSource();
    }

    // Create SqlSessionFactory
    @Bean
    public SqlSessionFactory sqlSessionFactoryBean() throws Exception {

        //Solving the problem of not nesting jar files under myBatis
        VFS.addImplClass(SpringBootVFS.class);

        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource());

        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();

        // Two * are directory wildcards
        sqlSessionFactoryBean.setMapperLocations(resolver
                .getResources("classpath:/mapper/**/*.xml"));

        //Specify the path to scan alias packages, scan paths for multiple bean s, and splice them separated by semicolons
        String typeAliasesPackage = "com.wzh.demo.domain;";

        sqlSessionFactoryBean.setTypeAliasesPackage(typeAliasesPackage);
        return sqlSessionFactoryBean.getObject();
    }

    // Create Things Manager
    @Bean
    public PlatformTransactionManager transactionManager() {
        return new DataSourceTransactionManager(dataSource());
    }
}

Solve the problem that setTypeAliases Package ("xxx") cannot find classes when Spring Boot integrates MyBatis into a jar

package com.wzh.application;

import java.io.IOException;
import java.net.URI;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.apache.ibatis.io.VFS;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;

/**
 * Spring Boot When integrating MyBatis into a jar, the class problem was not found
 * @author yuejing
 */
public class SpringBootVFS extends VFS {

    @Override
    public boolean isValid() {
        return true;
    }

    @Override
    protected List<String> list(URL url, String path) throws IOException {
        ClassLoader cl = this.getClass().getClassLoader();
        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(cl);
        Resource[] resources = resolver.getResources(path + "/**/*.class");
        List<Resource> resources1 = Arrays.asList(resources);
        List<String> resourcePaths = new ArrayList<String>();
        for (Resource resource: resources1) {
            resourcePaths.add(preserveSubpackageName(resource.getURI(), path));
        }
        return resourcePaths;
    }

    private static String preserveSubpackageName(final URI uri, final String rootPath) {
        final String uriStr = uri.toString();
        final int start = uriStr.indexOf(rootPath);
        return uriStr.substring(start, uriStr.length());
    }

}

Here I have a start-up test to see if there is any problem and it can start properly. Look at the log, there is a warn, because my mapper folder is empty.

Following is the overall test of the integration, and several demo folders are built to put these files.

Test class
bean

package com.wzh.demo.domain;

import java.io.Serializable;

public class UserBean implements Serializable{

    private static final long serialVersionUID = -2959897964759682757L;

    private Long id;
    private String name;
    private String sex;
    private Long age;

    public UserBean() {
        super();
        // TODO Auto-generated constructor stub
    }

    public UserBean(Long id, String name, String sex, Long age) {
        super();
        this.id = id;
        this.name = name;
        this.sex = sex;
        this.age = age;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public Long getAge() {
        return age;
    }

    public void setAge(Long age) {
        this.age = age;
    }


    @Override
    public String toString() {
        return "UserBean [id=" + id + ", name=" + name + ", sex=" + sex
                + ", age=" + age + "]";
    }

}

dao is the same as service. Here's just one

package com.wzh.demo.service.impl;

import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallbackWithoutResult;
import org.springframework.transaction.support.TransactionTemplate;

import com.wzh.demo.dao.UserDao;
import com.wzh.demo.domain.UserBean;
import com.wzh.demo.service.IUserService;


@Service("userService")
public class UserServiceImpl implements IUserService {

    @Autowired
    @Qualifier(value="userDao")
    private UserDao userDao;

    @Override
    public List<UserBean> selectUserByName(String name) {
        // TODO Auto-generated method stub
        return userDao.selectUserByName(name);
    }




}

mapper.java

package com.wzh.demo.mapper;

import java.util.List;

import com.wzh.demo.domain.UserBean;


public interface UserMapper {

    public List<UserBean> selectUserByName(String name);

}

mapper.xml

<?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.wzh.demo.mapper.UserMapper">


    <resultMap type="UserBean" id="user">
        <id property="id" column="id" />
        <result property="name" column="u_name" javaType="String" />
        <result property="sex" column="u_sex" javaType="String" />
        <result property="age" column="u_age" javaType="java.lang.Long" />
    </resultMap>

    <select id="selectUserByName" resultMap="user" parameterType="UserBean">
        select t.u_id,t.u_name,t.u_sex,t.u_age from t_user t where t.u_name =
        #{name}

    </select>

</mapper>

controller

package com.wzh.demo.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.wzh.demo.domain.UserBean;
import com.wzh.demo.service.IUserService;

@Controller
@RequestMapping("/user")
public class userTestController {

    @Autowired
    @Qualifier(value="userService")
    private IUserService userServiceImpl;

    @RequestMapping("/userInfo")
    public String showUserInfoByName(HttpServletRequest requset,HttpServletResponse response,Model mode)
    {

        //Here the name is written to death, and then only one is chosen for easy testing.
        UserBean user = userServiceImpl.selectUserByName("Zhang San").get(0);
        mode.addAttribute("user", user);

        return "/test/userInfo";

    }
}

ftl template

<!DOCTYPE html>
<html>
  <head>
    <title>MyHtml.html</title>

    <meta name="keywords" content="keyword1,keyword2,keyword3">
    <meta name="description" content="this is my page">
    <meta name="content-type" content="text/html; charset=UTF-8">

    <!--<link rel="stylesheet" type="text/css" href="./styles.css">-->

  </head>

  <body>
        Full name:<b>${user.name}</b></br>
        Gender:<b>${user.sex}</b></br>
        Age:<b>${user.age}</b></br>
  </body>
</html>

Browser direct access: http://localhost:8080/user/userInfo
Display effect

directory structure

So far this is the basic usage of spring boot. However, we will also encounter situations where no embedded Tomcat is required. We need to package it as war and deploy it to an external tomcat. Here's the modification section.
Modification of pom.xml

<groupId>com.wzh</groupId>
    <artifactId>SpringBootDemo</artifactId>
    <version>1.0-SNAPSHOT</version>
    <! - Modify the packaged file to war, and release this configuration if you need to deploy it to an external tomcat - >
    <!--<packaging>war</packaging>-->
<! - If you need to deploy to an external tomcat, you need to release this configuration - >.
        <!--
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <scope>provided</scope>
        </dependency>
        -->

Application.java Modification
Start class modification inherits SpringBootServletInitializer and overrides SpringApplication Builder method

package com.wzh.application;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.apache.ibatis.io.VFS;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.tomcat.jdbc.pool.DataSource;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.support.SpringBootServletInitializer;
/**
 * Spring Boot Apply the startup class, which inherits SpringBootServletInitializer and overrides the SpringApplication Builder method
 * To deploy external tomcat packaged as war
 */
@SpringBootApplication // Identifying Spring Boot applications
@ComponentScan(basePackages = { "com.wzh"}) // Specify the spring management path, which is the path for those bean annotations
@MapperScan({ "com.wzh.**.mapper" }) // The mapper interface class scans the package configuration with two * directory wildcards
public class Application extends SpringBootServletInitializer  {

    // Program Startup Entry
    public static void main(String[] args) {
        // Start embedded Tomcat and initialize Spring environment and its Spring components
        SpringApplication.run(Application.class, args);
    }

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(Application.class);
    }

    // Create the data source, because mybatis-spring 1.2 cancels the automatic injection of the data source, so you need to configure it manually.
    @Bean
    @ConfigurationProperties(prefix = "spring.datasource")// Specify the prefix of the data source, specified in the application.properties file
    public DataSource dataSource() {
        return new DataSource();
    }

    // Create SqlSessionFactory
    @Bean
    public SqlSessionFactory sqlSessionFactoryBean() throws Exception {

        //Solving the problem of not nesting jar files under myBatis
        VFS.addImplClass(SpringBootVFS.class);

        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource());

        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();

        // Two * are directory wildcards
        sqlSessionFactoryBean.setMapperLocations(resolver
                .getResources("classpath:/mapper/**/*.xml"));

        //Specify the path to scan alias packages, scan paths for multiple bean s, and splice them separated by semicolons
        String typeAliasesPackage = "com.wzh.demo.domain;";

        sqlSessionFactoryBean.setTypeAliasesPackage(typeAliasesPackage);
        return sqlSessionFactoryBean.getObject();
    }

    // Create Things Manager
    @Bean
    public PlatformTransactionManager transactionManager() {
        return new DataSourceTransactionManager(dataSource());
    }
}

application.properties modification

## Project name to facilitate project access
server.contextPath=/SpringBootDemo/

Now it's packaged as war. http://localhost:8080/SpringBootDemo/user/userInfo Visits were made.

Posted by jim35802 on Fri, 14 Dec 2018 15:00:04 -0800