spring boot+mybatis+mysql+FreeMarker整合

1.建立maven項目,jdk8以及以上,修改pom.xml,新增依賴css

<dependency>
	    <groupId>org.springframework.boot</groupId>
	    <artifactId>spring-boot-starter-parent</artifactId>
	    <version>1.5.2.RELEASE</version>
	    <type>pom</type>
	</dependency>
	<dependency>
	    <groupId>org.springframework.boot</groupId>
	    <artifactId>spring-boot-starter-web</artifactId>
	    <version>1.5.2.RELEASE</version>
	</dependency>
	<dependency>
	    <groupId>org.springframework</groupId>
	    <artifactId>spring-tx</artifactId>
	    <version>4.3.7.RELEASE</version>
	</dependency>
	<dependency>
	    <groupId>org.mybatis.spring.boot</groupId>
	    <artifactId>mybatis-spring-boot-starter</artifactId>
	    <version>1.2.0</version>
	</dependency>
	<dependency>
	    <groupId>com.alibaba</groupId>
	    <artifactId>druid</artifactId>
	    <version>1.0.25</version>
	</dependency>
	<dependency>
	    <groupId>com.baomidou</groupId>
	    <artifactId>mybatis-plus</artifactId>
	    <version>2.1.0</version>
	</dependency>
	<dependency>
	    <groupId>org.aspectj</groupId>
	    <artifactId>aspectjweaver</artifactId>
	    <version>1.8.4</version>
	</dependency>
	<dependency>
	    <groupId>mysql</groupId>
	    <artifactId>mysql-connector-java</artifactId>
	    <version>5.1.36</version>
	</dependency>
	<dependency>
	    <groupId>org.springframework.boot</groupId>
	    <artifactId>spring-boot-starter-freemarker</artifactId>
	    <version>1.5.9.RELEASE</version>
	</dependency>
	<dependency>
	    <groupId>org.freemarker</groupId>
	    <artifactId>freemarker</artifactId>
	    <version>2.3.22</version>
	</dependency>

2.配置DataSource,使用Druid做爲鏈接池html

package com.tany.demo.conf;

import java.sql.SQLException;

import javax.sql.DataSource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import com.alibaba.druid.pool.DruidDataSource;

/**
 * DataSource config
 * 
 * @author tanyong
 * @version $Id: DruidDataSourceConfig.java, v 0.1 2017年11月14日 上午11:50:25 tanyong Exp $
 */
@Configuration
@Primary
//在一樣的DataSource中,首先使用被標註的DataSource
public class DruidDataSourceConfig extends DataSourceProperties {

    private static final Logger logger = LoggerFactory.getLogger(DruidDataSourceConfig.class);

    /**
     * 數據庫連接地址
     */
    @Value("${jdbc.url}")
    private String              dbUrl;

    /**
     * jdbc user
     */
    @Value("${jdbc.user}")
    private String              username;

    /**
     * jdbc jdbc.pwd
     */
    @Value("${jdbc.pwd}")
    private String              password;

    /**
     * 驅動
     */
    @Value("${jdbc.driver}")
    private String              driverClassName;

    /**
     * 鏈接池初始化大小
     */
    @Value("${jdbc.initialSize}")
    private int                 initialSize;

    /**
     * 最小鏈接池數量
     */
    @Value("${jdbc.minIdle}")
    private int                 minIdle;

    /**
     * 鏈接池最大活動鏈接數
     */
    @Value("${jdbc.maxActive}")
    private int                 maxActive;

    /**
     * 獲取鏈接時最大等待時間,單位毫秒。配置了maxWait以後,缺省啓用公平鎖,併發效率會有所降低,
     * 若是須要能夠經過配置useUnfairLock屬性爲true使用非公平鎖。
     */
    @Value("${jdbc.maxWait}")
    private int                 maxWait;

    /**
     * 配置間隔多久才進行一次檢測,檢測須要關閉的空閒鏈接,單位是毫秒
     */
    @Value("${jdbc.timeBetweenEvictionRunsMillis}")
    private int                 timeBetweenEvictionRunsMillis;

    /**
     * 配置一個鏈接在池中最小生存的時間,單位是毫秒
     */
    @Value("${jdbc.minEvictableIdleTimeMillis}")
    private int                 minEvictableIdleTimeMillis;

    /**
     * 用來檢測鏈接是否有效的sql,要求是一個查詢語句。若是validationQuery爲null,
     * testOnBorrow、testOnReturn、testWhileIdle都不會其做用
     */
    @Value("${jdbc.validationQuery}")
    private String              validationQuery;

    /**
     * 建議配置爲true,不影響性能,而且保證安全性。申請鏈接的時候檢測,若是空閒時間大於timeBetweenEvictionRunsMillis,
     * 執行validationQuery檢測鏈接是否有效
     */
    @Value("${jdbc.testWhileIdle}")
    private boolean             testWhileIdle;

    /**
     * 申請鏈接時執行validationQuery檢測鏈接是否有效,作了這個配置會下降性能。
     */
    @Value("${jdbc.testOnBorrow}")
    private boolean             testOnBorrow;

    /**
     * 歸還鏈接時執行validationQuery檢測鏈接是否有效,作了這個配置會下降性能
     */
    @Value("${jdbc.testOnReturn}")
    private boolean             testOnReturn;

    /**
     * 是否緩存preparedStatement,也就是PSCache。PSCache對支持遊標的數據庫性能提高巨大,好比說oracle。在mysql下建議關閉。
     */
    @Value("${jdbc.poolPreparedStatements}")
    private boolean             poolPreparedStatements;

    /**
     * 每一個鏈接上PSCache的大小
     */
    @Value("${jdbc.maxPoolPreparedStatementPerConnectionSize}")
    private int                 maxPoolPreparedStatementPerConnectionSize;

    /**
     * 配置監控統計攔截的filters,去掉後監控界面sql沒法統計,'wall'用於防火牆
     */
    @Value("${jdbc.filters}")
    private String              filters;

    /**
     * 經過connectProperties屬性來打開mergeSql功能;慢SQL記錄
     */
    @Value("{jdbc.connectionProperties}")
    private String              connectionProperties;

    /**
     * 合併多個DruidDataSource的監控數據
     */
    @Value("{jdbc.useGlobalDataSourceStat}")
    private String              useGlobalDataSourceStat;

    @Bean
    public DataSource dataSource() {
        DruidDataSource datasource = new DruidDataSource();
        datasource.setUrl(this.dbUrl);
        datasource.setUsername(username);
        datasource.setPassword(password);
        datasource.setDriverClassName(driverClassName);

        //configuration  
        datasource.setInitialSize(initialSize);
        datasource.setMinIdle(minIdle);
        datasource.setMaxActive(maxActive);
        datasource.setMaxWait(maxWait);
        datasource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
        datasource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
        datasource.setValidationQuery(validationQuery);
        datasource.setTestWhileIdle(testWhileIdle);
        datasource.setTestOnBorrow(testOnBorrow);
        datasource.setTestOnReturn(testOnReturn);
        datasource.setPoolPreparedStatements(poolPreparedStatements);
        datasource
            .setMaxPoolPreparedStatementPerConnectionSize(maxPoolPreparedStatementPerConnectionSize);
        try {
            datasource.setFilters(filters);
        } catch (SQLException e) {
            logger.error("druid configuration initialization filter error:[{}]", e);
        }
        datasource.setConnectionProperties(connectionProperties);
        return datasource;
    }
}

3.配置Druid監控java

package com.tany.demo.conf;

import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;

@Configuration
public class DruidMonitorConfig {

    /**
     * 註冊ServletRegistrationBean
     * @return
     */
    @Bean
    public ServletRegistrationBean registrationBean() {
        ServletRegistrationBean bean = new ServletRegistrationBean(new StatViewServlet(),
            "/api/druid/*");
        /** 初始化參數配置,initParams**/
        //白名單
        //        bean.addInitParameter("allow", "127.0.0.1");//多個ip逗號隔開
        //IP黑名單 (存在共同時,deny優先於allow) : 若是知足deny的話提示:Sorry, you are not permitted to view this page.
        //bean.addInitParameter("deny", "192.168.1.73");
        //登陸查看信息的帳號密碼.
        bean.addInitParameter("loginUsername", "admin");
        bean.addInitParameter("loginPassword", "qaz123456");
        //是否可以重置數據.
        bean.addInitParameter("resetEnable", "false");
        return bean;
    }

    /**
     * 註冊FilterRegistrationBean
     * @return
     */
    @Bean
    public FilterRegistrationBean druidStatFilter() {
        FilterRegistrationBean bean = new FilterRegistrationBean(new WebStatFilter());
        //添加過濾規則.
        bean.addUrlPatterns("/*");
        //添加不須要忽略的格式信息.
        bean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/api/druid/*");
        return bean;
    }

}

4.mybaits plus 配置mysql

package com.tany.demo.conf;

import javax.sql.DataSource;

import org.apache.ibatis.mapping.DatabaseIdProvider;
import org.apache.ibatis.plugin.Interceptor;
import org.mybatis.spring.boot.autoconfigure.MybatisProperties;
import org.mybatis.spring.boot.autoconfigure.SpringBootVFS;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.ResourceLoader;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.TransactionManagementConfigurer;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

//import com.baomidou.mybatisplus.MybatisConfiguration;
//import com.baomidou.mybatisplus.MybatisXMLLanguageDriver;
import com.baomidou.mybatisplus.entity.GlobalConfiguration;
import com.baomidou.mybatisplus.enums.DBType;
import com.baomidou.mybatisplus.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.spring.MybatisSqlSessionFactoryBean;

/**
 * mybaits 配置
 * 
 * @author tanyong
 * @version $Id: MybatisPlusConfig.java, v 0.1 2017年11月15日 下午3:19:49 tanyong Exp $
 */
@Configuration
@EnableConfigurationProperties(MybatisProperties.class)
public class MybatisPlusConfig implements TransactionManagementConfigurer {

    @Autowired
    private DataSource         dataSource;

    @Autowired
    private MybatisProperties  properties;

    @Autowired
    private ResourceLoader     resourceLoader = new DefaultResourceLoader();

    @Autowired(required = false)
    private Interceptor[]      interceptors;

    @Autowired(required = false)
    private DatabaseIdProvider databaseIdProvider;

    /**
     *	 mybatis-plus分頁插件
     */
    @Bean
    public PaginationInterceptor paginationInterceptor() {
        PaginationInterceptor page = new PaginationInterceptor();
        page.setDialectType("mysql");
        return page;
    }

    /**
     * 聲明默認 transactionManager
     * 
     * @return
     */
    public PlatformTransactionManager transactionManager() {
        DataSourceTransactionManager sourceTransactionManager = new DataSourceTransactionManager();
        sourceTransactionManager.setDataSource(dataSource);
        return sourceTransactionManager;
    }

    /**
     * 默認transactionManager
     * @see org.springframework.transaction.annotation.TransactionManagementConfigurer#annotationDrivenTransactionManager()
     */
    @Override
    public PlatformTransactionManager annotationDrivenTransactionManager() {
        return transactionManager();
    }

    /**
     * 這裏所有使用mybatis-autoconfigure 已經自動加載的資源。不手動指定
     * 配置文件和mybatis-boot的配置文件同步
     * @return
     */
    @Bean
    public MybatisSqlSessionFactoryBean mybatisSqlSessionFactoryBean() {
        MybatisSqlSessionFactoryBean mybatisPlus = new MybatisSqlSessionFactoryBean();
        mybatisPlus.setDataSource(dataSource);
        mybatisPlus.setVfs(SpringBootVFS.class);
        if (StringUtils.hasText(this.properties.getConfigLocation())) {
            mybatisPlus.setConfigLocation(
                this.resourceLoader.getResource(this.properties.getConfigLocation()));
        }
        mybatisPlus.setConfiguration(properties.getConfiguration());
        if (!ObjectUtils.isEmpty(this.interceptors)) {
            mybatisPlus.setPlugins(this.interceptors);
        }
        // MP 全局配置,更多內容進入類看註釋
        GlobalConfiguration globalConfig = new GlobalConfiguration();
        globalConfig.setDbType(DBType.MYSQL.name());//數據庫類型
        // ID 策略 AUTO->`0`("數據庫ID自增") INPUT->`1`(用戶輸入ID") ID_WORKER->`2`("全局惟一ID") UUID->`3`("全局惟一ID")
        globalConfig.setIdType(0);
        //MP 屬性下劃線 轉 駝峯 , 若是原生配置 mc.setMapUnderscoreToCamelCase(true) 開啓,該配置能夠無。
        //globalConfig.setDbColumnUnderline(true);
        mybatisPlus.setGlobalConfig(globalConfig);
        //        MybatisConfiguration mc = new MybatisConfiguration();
        //        // 對於徹底自定義的mapper須要加此項配置,才能實現下劃線轉駝峯
        //        //mc.setMapUnderscoreToCamelCase(true);
        //        mc.setDefaultScriptingLanguage(MybatisXMLLanguageDriver.class);
        //        mybatisPlus.setConfiguration(mc);
        if (this.databaseIdProvider != null) {
            mybatisPlus.setDatabaseIdProvider(this.databaseIdProvider);
        }
        if (StringUtils.hasLength(this.properties.getTypeAliasesPackage())) {
            mybatisPlus.setTypeAliasesPackage(this.properties.getTypeAliasesPackage());
        }
        if (StringUtils.hasLength(this.properties.getTypeHandlersPackage())) {
            mybatisPlus.setTypeHandlersPackage(this.properties.getTypeHandlersPackage());
        }
        if (!ObjectUtils.isEmpty(this.properties.resolveMapperLocations())) {
            mybatisPlus.setMapperLocations(this.properties.resolveMapperLocations());
        }
        return mybatisPlus;
    }

}

5.FreeMarkerConfig 配置web

package com.tany.demo.conf;

import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.freemarker.FreeMarkerProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver;

/**
 * 
 * FreeMarkerConfig
 * @author tanyong
 * @version $Id: FreeMarkerConfig.java, v 0.1 2018年2月27日 下午5:25:46 ThinkPad Exp $
 */
@Configuration
public class FreeMarkerConfig {

    @Bean
    @ConditionalOnMissingBean(FreeMarkerConfig.class)
    public FreeMarkerConfigurer freeMarkerConfigurer() {
        FreeMarkerConfigurer configurer = new FreeMarkerConfigurer();
        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        configurer.setConfigLocation(resolver.getResource("classpath:/freemarker.properties"));
        configurer.setTemplateLoaderPath(FreeMarkerProperties.DEFAULT_TEMPLATE_LOADER_PATH);
        configurer.setPreferFileSystemAccess(true);
        configurer.setDefaultEncoding("UTF-8");
        return configurer;
    }
    
    @Bean
    @ConditionalOnMissingBean(name = "freeMarkerViewResolver")
    @ConditionalOnProperty(name = "spring.freemarker.enabled", matchIfMissing = true)
    public FreeMarkerViewResolver freeMarkerViewResolver() {
        FreeMarkerViewResolver viewResolver = new FreeMarkerViewResolver();
        viewResolver.setCache(true);
        viewResolver.setContentType("text/html;charset=UTF-8");
        //resolver.setViewNames(getViewNames());
        viewResolver.setExposeRequestAttributes(true);
        viewResolver.setAllowRequestOverride(true);
        viewResolver.setAllowSessionOverride(true);
        viewResolver.setExposeSessionAttributes(true);
        viewResolver.setExposeSpringMacroHelpers(true);
        viewResolver.setRequestContextAttribute("request");
        viewResolver.setOrder(Ordered.LOWEST_PRECEDENCE - 5);
        viewResolver.setSuffix(".ftl");
        viewResolver.setPrefix("/");
        return viewResolver;
    }
}

6.在src/main/resources 新建application.propertiesspring

#測試環境
spring.profiles.active=test
#生產環境
#spring.profiles.active=prod


根據不一樣的環境,新建不一樣的配置文件,測試環境配置文件application-test.properties
#mysql
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
#jdbc.dialect=org.hibernate.dialect.MySQLDialect
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost/test
jdbc.user=user
jdbc.pwd=passwd
jdbc.initialSize=5
jdbc.minIdle=5
jdbc.maxActive=20
jdbc.maxWait=600000
jdbc.timeBetweenEvictionRunsMillis=600000
jdbc.minEvictableIdleTimeMillis=300000
jdbc.validationQuery=SELECT 1 FROM DUAL
jdbc.testWhileIdle=true
jdbc.testOnBorrow=false
jdbc.testOnReturn=false
jdbc.poolPreparedStatements=false
jdbc.maxPoolPreparedStatementPerConnectionSize=20
jdbc.filters=stat,wall,log4j
jdbc.connectionProperties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
jdbc.useGlobalDataSourceStat=true

debug=true
spring.http.encoding.charset=UTF-8
spring.http.encoding.force=true
spring.mvc.favicon.enabled=false

#mybatis
mybatis.configLocation=classpath:mybatis-config.xml
mybatis.mapper-locations=classpath:com/tany/demo/mapper/xml/*Mapper.xml
mybatis.typeAliasesPackage=com.tany.demo.entity

新建freemarker.properties

locale=CHINA
default_encoding=UTF-8
output_encoding=UTF-8
number_format=#.##
date_format=yyyy-MM-dd
time_format=HH:mm:Ss
datetime_format=yyyy-MM-dd HH:mm:Ss
template_update_delay=0
auto_import="/global_library.ftl" as model

新建logback.xml
<?xml version="1.0" encoding="UTF-8"?>

<!-- 
debug : 默認爲false ,設置爲true時,將打印出logback內部日誌信息,實時查看logback運行狀態。
scan : 配置文件若是發生改變,將會從新加載,默認值爲true;
scanPeriod : 檢測配置文件是否有修改的時間間隔,若是沒有給出時間單位,默認單位時毫秒,當scan爲true時,這個屬性生效,默認時間間隔爲1min。
 -->
<configuration debug="false" scan="true" scanPeriod="1000 seconds">
	<timestamp key="date" datePattern="yyyyMMdd" />
	<!-- Output to Console -->
	<appender name="Console" class="ch.qos.logback.core.ConsoleAppender">
		<encoder>
			<pattern>%d{yyyy-MM-dd HH:mm:ss} %level %c:%L - %msg%n</pattern>
			<charset>UTF-8</charset>
		</encoder>
	</appender>
	<!-- Output to File -->
	<appender name="file_log" class="ch.qos.logback.core.rolling.RollingFileAppender">
		<File>${user.dir}/logs/catalina.log</File>
		<filter class="ch.qos.logback.classic.filter.LevelFilter">
              <!-- 過濾掉非INFO級別 -->
              <level>INFO</level>
              <onMatch>ACCEPT</onMatch>
              <onMismatch>DENY</onMismatch>
        </filter>
		<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
			<FileNamePattern>
				${user.dir}/logs/catalina.log.%d{yyyy-MM-dd}
			</FileNamePattern>
			<!-- keep 1 days worth of history -->
			<MaxHistory>30</MaxHistory>
		</rollingPolicy>
		<encoder>
			<pattern>%d{yyyy-MM-dd HH:mm:ss} %level %c:%L - %msg%n</pattern>
			<charset>UTF-8</charset>
		</encoder>
	</appender>
	<!-- 打印級別,大小寫無關:TRACE, DEBUG, INFO, WARN, ERROR, ALL 和  OFF 默認是DEBUG -->
	<root level="INFO">
        <appender-ref ref="Console" />
		<appender-ref ref="file_log" />
	</root>
	<logger name="org.springframework" level="ERROR" />
	<logger name="com.tany.demo.mapper" level="DEBUG" />
</configuration>


新建mybatis-config.xml

<?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>
	<settings>
		<!-- 全局映射器不啓用緩存 -->
		<setting name="cacheEnabled" value="true" />
		<!-- 查詢時,關閉關聯對象即時加載以提升性能 -->
		<setting name="lazyLoadingEnabled" value="false" />
		<!-- 設置關聯對象加載的形態,此處爲按需加載字段(加載字段由SQL指定),不會加載關聯表的全部字段,以提升性能 -->
		<setting name="aggressiveLazyLoading" value="false" />
		<!-- 對於未知的SQL查詢,容許返回不一樣的結果集以達到通用的效果 -->
		<setting name="multipleResultSetsEnabled" value="true" />
		<!-- 容許使用列標籤代替列名 -->
		<setting name="useColumnLabel" value="true" />
		<!-- 容許使用自定義的主鍵值(好比由程序生成的UUID 32位編碼做爲鍵值),數據表的PK生成策略將被覆蓋 -->
		<setting name="useGeneratedKeys" value="true" />
		<!-- 給予被嵌套的resultMap以字段-屬性的映射支持 -->
		<setting name="autoMappingBehavior" value="PARTIAL" />
		<!-- 對於批量更新操做緩存SQL以提升性能 -->
		<setting name="defaultExecutorType" value="SIMPLE" />
		<!-- 數據庫超過25000秒仍未響應則超時 -->
		<setting name="defaultStatementTimeout" value="25000" />
<!-- 		<setting name="logImpl" value="STDOUT_LOGGING" /> -->
	</settings>
</configuration>

到此配置文件已經建立完成,如今編寫model層代碼 7.在com.tany.demo.entity包下建立SysUsersql

package com.tany.demo.entity;

import com.baomidou.mybatisplus.annotations.TableField;
import com.baomidou.mybatisplus.annotations.TableId;
import java.util.Date;
import com.baomidou.mybatisplus.enums.IdType;
import com.baomidou.mybatisplus.activerecord.Model;
import com.baomidou.mybatisplus.annotations.TableName;
import java.io.Serializable;

/**
 * <p>
 * 
 * </p>
 *
 * @author tanyong
 * @since 2017-04-06
 */
@TableName("sys_user")
public class SysUser extends Model<SysUser> {

    private static final long serialVersionUID = 1L;

    /**
     * 父帳號ID
     */
    @TableField("parent_id")
    private Integer           parentId;
    /**
     * 主鍵 運營平臺用戶ID
     */
    @TableId(value = "id", type = IdType.AUTO)
    private Integer           id;
    /**
     * 登錄帳號名	惟一性約束
     */
    private String            username;
    /**
     * 登錄密碼	MD5加密
     */
    private String            password;
    /**
     * 聯繫人
     */
    private String            name;
    /**
     * 聯繫電話
     */
    private String            telephone;
    /**
     * 狀態	0:可用 1:停用
     */
    private Integer           status;
    /**
     * 刪除狀態	0:正常 1:刪除
     */
    @TableField("delete_flag")
    private Integer           deleteFlag;
    /**
     * 備註
     */
    private String            remark;
    /**
     * 最近一次登陸的IP
     */
    @TableField("login_ip")
    private String            loginIp;
    /**
     * 最近一次登陸的時間
     */
    @TableField("login_time")
    private Date              loginTime;
    /**
     * 帳戶建立時間
     */
    @TableField("create_time")
    private Date              createTime;
    /**
     * 帳戶修改時間
     */
    @TableField("update_time")
    private Date              updateTime;
    /**
     * 刪除時間
     */
    @TableField("delete_time")
    private Date              deleteTime;

    @TableField(exist = false)
    private Integer[]         menuIds;

    @TableField(exist = false)
    private String            roleName;

    public String getRoleName() {
        return roleName;
    }

    public void setRoleName(String roleName) {
        this.roleName = roleName;
    }

    public Integer[] getMenuIds() {
        return menuIds;
    }

    public void setMenuIds(Integer[] menuIds) {
        this.menuIds = menuIds;
    }

    public Integer getParentId() {
        return parentId;
    }

    public void setParentId(Integer parentId) {
        this.parentId = parentId;
    }

    public Integer getId() {
        return id;
    }

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

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getName() {
        return name;
    }

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

    public String getTelephone() {
        return telephone;
    }

    public void setTelephone(String telephone) {
        this.telephone = telephone;
    }

    public Integer getStatus() {
        return status;
    }

    public void setStatus(Integer status) {
        this.status = status;
    }

    public Integer getDeleteFlag() {
        return deleteFlag;
    }

    public void setDeleteFlag(Integer deleteFlag) {
        this.deleteFlag = deleteFlag;
    }

    public String getRemark() {
        return remark;
    }

    public void setRemark(String remark) {
        this.remark = remark;
    }

    public String getLoginIp() {
        return loginIp;
    }

    public void setLoginIp(String loginIp) {
        this.loginIp = loginIp;
    }

    public Date getLoginTime() {
        return loginTime;
    }

    public void setLoginTime(Date loginTime) {
        this.loginTime = loginTime;
    }

    public Date getCreateTime() {
        return createTime;
    }

    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }

    public Date getUpdateTime() {
        return updateTime;
    }

    public void setUpdateTime(Date updateTime) {
        this.updateTime = updateTime;
    }

    public Date getDeleteTime() {
        return deleteTime;
    }

    public void setDeleteTime(Date deleteTime) {
        this.deleteTime = deleteTime;
    }

    @Override
    protected Serializable pkVal() {
        return this.id;
    }

}

8,在com.tany.demo.mapper包下建立 SysUserMapper數據庫

package com.tany.demo.mapper;

import com.baomidou.mybatisplus.mapper.BaseMapper;
import com.tany.demo.entity.SysUser;

/**
 * <p>
  *  Mapper 接口
 * </p>
 *
 * @author tanyong
 * @since 2017-04-06
 */
public interface SysUserMapper extends BaseMapper<SysUser> {

}


9.在com.tany.demo.mapper.xml 建立SysUserMapper.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.daogou.mapper.SysUserMapper">

	<!-- 通用查詢映射結果 -->
	<resultMap id="BaseResultMap" type="com.tany.demo.entity.SysUser">
		<id column="id" property="id" />
		<result column="parent_id" property="parentId" />
		<result column="username" property="username" />
		<result column="password" property="password" />
		<result column="name" property="name" />
		<result column="telephone" property="telephone" />
		<result column="status" property="status" />
		<result column="delete_flag" property="deleteFlag" />
		<result column="remark" property="remark" />
		<result column="login_ip" property="loginIp" />
		<result column="login_time" property="loginTime" />
		<result column="create_time" property="createTime" />
		<result column="update_time" property="updateTime" />
		<result column="delete_time" property="deleteTime" />
		<result column="role_name" property="roleName" />
	</resultMap>
</mapper>

10.在com.tany.demo.service包下建立 ISysUserServiceapache

package com.tany.demo.service;

import com.baomidou.mybatisplus.service.IService;
import com.tany.demo.entity.SysUser;
/**
 * 
 * 
 * @author tanyong
 * @version $Id: ISysUserService.java, v 0.1 2018年2月27日 下午4:52:17 ThinkPad Exp $
 */
public interface ISysUserService extends IService<SysUser> {

}


11.在com.tany.demo.service.impl包下建立
package com.tany.demo.service.impl;

import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.tany.demo.entity.SysUser;
import com.tany.demo.mapper.SysUserMapper;
import com.tany.demo.service.ISysUserService;
/**
 * 
 * 
 * @author tanyong
 * @version $Id: SysUserServiceImpl.java, v 0.1 2018年2月27日 下午4:53:34 ThinkPad Exp $
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser>
                                implements ISysUserService {

}


11.建立Controller 在com.tany.demo.controller 包下建立UserController


package com.tany.demo.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.tany.demo.entity.SysUser;
import com.tany.demo.service.ISysUserService;

/**
 * 
 * 
 * @author tanyong
 * @version $Id: UserController.java, v 0.1 2018年2月27日 下午5:29:12 ThinkPad Exp $
 */
@RequestMapping("/user")
@Controller
public class UserController {

    @Autowired
    private ISysUserService userService;

    @RequestMapping("/list")
    public String list(Model model) {
        model.addAttribute("obj", userService.selectList(new EntityWrapper<SysUser>()));
        return "list";
    }
}

12.建立Controller 對應的視圖 在src/main/resources新建templates文件夾,在文件夾下新建global_library.ftlapi

<#assign static_domain = "https://you.static.com">
<#assign static_version = "20170906">

<#assign basePath = request.contextPath>

<#--插入頁面 -->
<#macro include page>
<#include "${page}">
</#macro>

新建 list.ftl

<#if ((obj)?exists && (obj)?size >0)>
     <#list obj as l>
             ${(l.username)!}</br>
     </#list>
</#if>

13,建立 app啓動類 在com.tany.demo包下建立Application.java

package com.tany.demo;

import javax.servlet.MultipartConfigElement;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.Banner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.embedded.ConfigurableEmbeddedServletContainer;
import org.springframework.boot.context.embedded.EmbeddedServletContainerCustomizer;
import org.springframework.boot.web.servlet.MultipartConfigFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.transaction.annotation.EnableTransactionManagement;

/**
 * 
 * 
 * @author tanyong
 * @version $Id: Application.java, v 0.1 2018年2月27日 下午2:43:43 ThinkPad Exp $
 */
@Configuration
@ComponentScan({ "com.tany.demo" })
@MapperScan("com.tany.demo.mapper")
//#表示開啓AOP代理自動配置,若是配@EnableAspectJAutoProxy表示使用cglib進行代理對象的生成;
//設置@EnableAspectJAutoProxy(exposeProxy=true)表示經過aop框架暴露該代理對象,aopContext可以訪問.
@EnableAspectJAutoProxy
@SpringBootApplication
//#使用@ServletComponentScan 註解後,Servlet、Filter、Listener 能夠直接經過 @WebServlet、@WebFilter、@WebListener 註解自動註冊,無需其餘代碼
//@ServletComponentScan
@EnableTransactionManagement // 等同<tx:annotation-driven/>
public class Application implements EmbeddedServletContainerCustomizer {

    private static String port = "8081";

    public static void main(String[] args) {
        for (String arg : args) {
            if (arg.startsWith("-httpPort")) {
                String p = arg.substring(arg.indexOf("=") + 1);
                if (Integer.valueOf(p) > 0) {
                    port = p;
                }
            }
        }
        SpringApplication app = new SpringApplication(Application.class);
        app.setBannerMode(Banner.Mode.OFF);
        // app.setDefaultProperties(defaultProperties());
        app.run(args);
    }

    /**
     * 自定義端口
     * @see org.springframework.boot.context.embedded.EmbeddedServletContainerCustomizer#customize(org.springframework.boot.context.embedded.ConfigurableEmbeddedServletContainer)
     */
    @Override
    public void customize(ConfigurableEmbeddedServletContainer container) {
        container.setPort(Integer.valueOf(port));
    }

    /**
     * 自定義上傳配置
     * 
     * @return
     */
    @Bean
    public MultipartConfigElement multipartConfigElement() {
        MultipartConfigFactory factory = new MultipartConfigFactory();
        // 單個文件最大
        factory.setMaxFileSize("3MB"); // KB,MB
        // / 設置總上傳數據總大小
        factory.setMaxRequestSize("10MB");
        return factory.createMultipartConfig();
    }
}

到此整合完畢,直接啓動運行

相關文章
相關標籤/搜索