Spring boot Getting Started five spring MVC Spring boot mybatis configuration consolidation

Source: Internet
Author: User
Tags foreach bind datetime xmlns tomcat


remark:

A basic understanding of spring boot has been made through the previous chapters, but spring boot is just a box that encapsulates an integrated reference and needs to be combined with a specific project to really use it.


The main record is to use spring boot to implement the integration of spring MVC and MyBatis:


The specific configuration is as follows:


1. Create a MAVEN project, either a Web project or a basic MAVEN project,


2, Configuration Pom.xml

<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/maven-v4_0_0.xsd" > <modelversion >4.0.0</modelVersion> <groupId>com.sam.project</groupId> <artifactid>spring_boot_mvc </artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name >spring_boot_mvc Maven webapp</name> <url>http://maven.apache.org</url> <parent> < Groupid>org.springframework.boot</groupid> <artifactid>spring-boot-starter-parent</artifactid > <version>1.5.1.RELEASE</version> </parent> <properties> <webversion>3.1</web version> </properties> <dependencies> <dependency> <groupid>org.springframework.boot&lt ;/groupid> <artifactid>spring-boot-starter-web</artifactid> <exclusions> <exclusion> <artifactId>log4j-over-slf4j</artifactId> <group id>org.slf4j</groupid> </exclusion> <exclusion> <groupid>org.springframework.boot& lt;/groupid> <artifactId>spring-boot-starter-tomcat</artifactId> </exclusion> </exclus ions> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <arti Factid>spring-boot-starter-tomcat</artifactid> <scope>provided</scope> </dependency> & Lt;dependency> <groupId>org.springframework.boot</groupId> <artifactId>

		Spring-boot-configuration-processor</artifactid> <optional>true</optional> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId> Spring-boot-starter-jdbc</artifactid> </dependency> <dEpendency> <groupId>org.springframework.boot</groupId> &LT;ARTIFACTID&GT;SPRING-BOOT-STARTER-AOP </artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactid& Gt;mysql-connector-java</artifactid> </dependency> <!--mybatis--<dependency> <group
			Id>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.11</version> </dependency> <!--spring Boot tomcat JSP support on-<dependency> <groupid>org.apache.tomcat.embed</groupid&gt
			; <artifactId>tomcat-embed-jasper</artifactId> </dependency> <!--servlet support on-<depende Ncy> <groupid>javax.servleT</groupid> <artifactId>javax.servlet-api</artifactId> </dependency> <!--jstl support Open--&G
		T <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> </de pendency> </dependencies> <build> <plugins> <plugin> <artifactid>maven-compil er-plugin</artifactid> <configuration> <source>1.8</source> <target>1.8</ta
 rget> </configuration> </plugin> </plugins> </build> </project>


3. Configuration Properties File

Create application.properties under the resources directory

#数据源驱动
jdbc.ds.url=jdbc:mysql://localhost/springboot?autoreconnect=true&useunicode=true& Characterencoding=utf-8&zerodatetimebehavior=converttonull
jdbc.ds.username=root
jdbc.ds.password= Root
jdbc.ds.driver-class-name=com.mysql.jdbc.driver

#mybatis配置    
mybatis.type-aliases-package= Com.sam.project.*.model
mybatis.mapper-locations=classpath:mapper/*.xml

server.port=8088
Server.contextpath=/spring_boot
#设置环境配置
#spring. Profiles.active=dev


#http encoding
Spring.http.encoding.charset=utf-8
spring.http.encoding.enabled=true
spring.http.encoding.force=true


#日志
logging.file=/export/log
logging.level.root=info
Logging.level.org.springframework.web=info
logging.level.sample.mybatis.mapper=trace

#关闭启动Logo
Spring.main.banner-mode=off


#设置mvc页面跳转
spring.mvc.view.prefix=/web-inf/jsp/
spring.mvc.view.suffix=.jsp


4, Configuration MyBatis

1), create mapper interface file

Package com.sam.project.mvc.mapper;

Import java.util.List;

Import Com.sam.project.mvc.model.User;

/**
 * @ClassName: Usermapper 
 * @Description: mybites data Query interface */public
interface Usermapper {

	List <User> querylist ();

	void Save (user user);

	void Batchdelete (integer[] IDs);

	void update (user user);




2), create Mapper.xml

Create the Mapper directory under the Resources directory and create the Usermapper.xml

/mapper/usermapper.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.sam.project.mvc.mapper.UserMapper" > <select id= "querylist" resulttype= " Com.sam.project.mvc.model.User "> select U.id, U.username, U.password, U.email, u.useable, U.addtime, U.logintime, U. Loginip from T_user u </select> <select id= "Querybyid" resulttype= "Com.sam.project.mvc.model.User" > Sele CT u.id, U.username, U.password, U.email, u.useable, U.addtime, U.logintime, u.loginip from T_user u where u.id = #{id} & Lt;/select> <insert id= "save" > INSERT into T_user (username, password, email, useable, addtime) VALUES (#{us Ername}, #{password}, #{email}, #{useable}, now ()) </insert> <update id= "Update" > Update T_user Set Pass Word = #{password}, email = #{email}, useable = #{useable} where id = #{id} </update> <delete id= "Batchdelete "; Delete from T_user where ID in <foreach collection= "array" item= "Item" open= "(" separator= "," close= ")" > #{item } </foreach> </delete> <!--<delete id= "delusers" > Delete from T_user where ID in <forea CH collection= "List" item= "Item" open= "(" separator= "," close= ")" > #{item} </foreach> </delete>--&gt
; </mapper>


3), create entity classes

Package Com.sam.project.mvc.model;

	/** * @ClassName: User * @Description: Entity model */public class User {private Integer ID;

	Private String username;

	private String password;

	Private String Email;

	/** * is available (0 disabled, 1 available) */private Integer useable;

	/** * Create time */private String addtime;

	/** * Login Time */private String logintime;

	/** * Login IP */private String Loginip;
	/** * @return ID */public Integer getId () {return id;
	}/** * @param ID */public void setId (Integer id) {this.id = ID;
	}/** * @return username */public String GetUserName () {return username;
	}/** * @param username */public void Setusername (String username) {this.username = username;
	}/** * @return password */public String GetPassword () {return password;
	}/** * @param password */public void SetPassword (String password) {this.password = password;
	}/** * @return Email */Public String Getemail () {return email;
}
	/** * @param email * * public void Setemail (String email) {this.email = email;
	}/** * Gets available (0 disabled, 1 available) * * @return useable-available (0 disabled, 1 available) */public Integer getuseable () {return useable; }/** * settings are available (0 disabled, 1 available) * * @param useable * Available (0 disabled, 1 available) */public void setuseable (Integer usea
	BLE) {this.useable = useable;
	}/** * Get creation time * * @return Addtime-Create Time */public String Getaddtime () {return addtime; }/** * Set creation time * * @param addtime * Create time */public void Setaddtime (String addtime) {This.addtim
	e = Addtime;
	/** * Get Login time * * @return Logintime-Login Time */public String Getlogintime () {return logintime; /** * Set Login time * * @param logintime * Login time */public void Setlogintime (String logintime) {this.
	Logintime = Logintime;
	}/** * Get login IP * * @return loginip-Login IP */public String Getloginip () {return loginip; }/** * Set the login IP * * @param Loginip * Login IP */public void Setloginip (String loginip) {this.loginip = Loginip; }
}


4), Create service Business processing class UserService

Package com.sam.project.mvc.service;

Import java.util.List;
Import org.springframework.beans.factory.annotation.Autowired;

Import Org.springframework.stereotype.Service;
Import Com.sam.project.mvc.common.AjaxResult;
Import Com.sam.project.mvc.mapper.UserMapper;

Import Com.sam.project.mvc.model.User;
	
	@Service public class UserService {@Autowired private usermapper usermapper;
		Public Ajaxresult querylist () {list<user> List = usermapper.querylist ();
	return new Ajaxresult (list);
		Public Ajaxresult Save (user user) {user.setusername ("user" + System.currenttimemillis ());
		User.setpassword ("123456");
		User.setemail ("User" + System.currenttimemillis () + "@test. com");
		User.setuseable (1);
		Usermapper.save (user);
	return new Ajaxresult ();
		} public Ajaxresult Batchdelete (integer[] IDs) {usermapper.batchdelete (IDS);
	return new Ajaxresult ();
		Public ajaxresult Update (user user) {usermapper.update (user);
	return new Ajaxresult ();
 }

}


4. Configuring Controller class Usercontroller

Package Com.sam.project.mvc.controller;
Import org.springframework.beans.factory.annotation.Autowired;
Import Org.springframework.stereotype.Controller;
Import org.springframework.web.bind.annotation.RequestMapping;

Import Org.springframework.web.bind.annotation.ResponseBody;
Import Com.sam.project.mvc.common.AjaxResult;
Import Com.sam.project.mvc.model.User;

Import Com.sam.project.mvc.service.UserService; /** * @ClassName: Usercontroller * @Description: User Controller */@Controller public class Usercontroller {@Autowire
	
	D Private UserService UserService;
	@ResponseBody @RequestMapping ("/querylist") public Ajaxresult querylist () {return userservice.querylist ();
	} @ResponseBody @RequestMapping ("/adduser") public ajaxresult addUser (user user) {return userservice.save (user); } @ResponseBody @RequestMapping ("/deluser") public Ajaxresult Deluser (integer[] IDs) {return Userservice.batchdele
	Te (IDs); } @ResponseBody @RequestMapping ("/updateuser") public AjaXresult updateUser (user user) {return userservice.update (user);
 }

}


5. Configuring Database Processing Classes

Package Com.sam.project.mvc.common;

Import Javax.sql.DataSource;

Import Org.mybatis.spring.annotation.MapperScan;
Import org.springframework.boot.context.properties.ConfigurationProperties;
Import Org.springframework.context.annotation.Bean;
Import org.springframework.context.annotation.Configuration;

Import Com.alibaba.druid.pool.DruidDataSource;

/**
 * @ClassName: Datasourceconfiguration 
 * @Description: Single Data source configuration */
@Configuration
@ Mapperscan (basepackages = "Com.sam.project.*.mapper") public
class Datasourceconfiguration {

    @Bean
    @ Configurationproperties (prefix = "jdbc.ds") public
    DataSource Readdatasource () {
        return new Druiddatasource ();
    }
}

Database creation Script:

CREATE TABLE ' t_user ' (
  ' id ' int (one) not NULL,
  ' username ' varchar (255) Default NULL,
  ' password ' varchar (255) Default NULL,
  ' email ' varchar (255) default NULL,
  ' useable ' int () default null,
  ' addtime ' datetime default NULL,
  ' logintime ' datetime default NULL,
  ' loginip ' varchar (255) default NULL,
  PRIMARY KEY  (' id ')
) Engine=innodb DEFAULT Charset=utf8;




6, write a test Jason returns the common class

Package Com.sam.project.mvc.common;
	/** * @ClassName: Ajaxresult * @Description: Package return Data */public class Ajaxresult {private int retcode = 1;
	Private String retmsg = "Operation succeeded";
	
	Private Object data;
		Public Ajaxresult (int retcode, String retmsg, Object data) {This.retcode = Retcode;
		This.retmsg = retmsg;
	This.data = data;
		} public Ajaxresult (int retcode, String retmsg) {this.retcode = Retcode;
	This.retmsg = retmsg;
		Public Ajaxresult (Object data) {this.retmsg = "query succeeded";
	This.data = data;
		} public ajaxresult (int retcode) {this.retcode = Retcode;
	This.retmsg = "Operation failed";
		} public Ajaxresult (String retmsg) {this.retcode = 0;
	This.retmsg = retmsg;
	} public Ajaxresult () {} public int getretcode () {return retcode;
	} public void Setretcode (int retcode) {this.retcode = Retcode;
	} public String getretmsg () {return retmsg;
	} public void Setretmsg (String retmsg) {this.retmsg = retmsg; } public Object GetData () {return data;
	} public void SetData (Object data) {this.data = data; } @Override Public String toString () {return "Ajaxresult [retcode=" + Retcode + ", retmsg=" + retmsg + ", data=" + D
	ATA + "]";
 }
	
}



7. Create a boot entry:

Package COM.SAM.PROJECT.MVC;

Import org.springframework.boot.SpringApplication;
Import org.springframework.boot.autoconfigure.SpringBootApplication;
Import Org.springframework.boot.builder.SpringApplicationBuilder;
Import Org.springframework.boot.web.support.SpringBootServletInitializer;
Import org.springframework.cache.annotation.EnableCaching;

/**
 * @ClassName: Application 
 * @Description: Springboot launcher *
///Open cache
@EnableCaching
@SpringBootApplication public
class application extends Springbootservletinitializer {

	@Override
	Protected Springapplicationbuilder Configure (Springapplicationbuilder application) {
		return Application.sources (Application.class);
	}

	public static void Main (string[] args) {
		springapplication.run (application.class, args);
	}
}


Well, at this point, the configuration is complete, after the creation is complete the directory is as follows:




Start the application class Main method to open spring boot

Since the page is not being made, the direct access to the back-end method after the boot is complete http://localhost:8088/spring_boot/queryList






This is done using Spring boot configuration Spring MVC and MyBatis.




Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.