Spring Boot self-study Note (ii) integrated MyBatis

Source: Internet
Author: User
Tags bind connection pooling xmlns

Spring Boot official website does not provide an integrated MyBatis example, csnd or there are a lot of related technical articles, can learn from, the following is my own write integration, can do reference.


Pom.xml adding mybatis and data connection pooling dependencies, personal habits using C0P3 connection pooling

<?xml version= "1.0" encoding= "UTF-8"?> <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.vic
		</groupId> <artifactId>vic</artifactId> <version>0.1.0</version> <properties> <java.version>1.7</java.version> </properties> <parent> <groupId> Org.springframework.boot</groupid> <artifactId>spring-boot-starter-parent</artifactId> < Version>1.3.8.release</version> </parent> <dependencies> <!--Spring Boot-to-<depend Ency> <groupId>org.springframework.boot</groupId> <artifactid>spring-boot-starter-web</ Artifactid> </dependency> <!--mybatis--<dependency> <groupiD>org.springframework.boot</groupid> <artifactId>spring-boot-starter-jdbc</artifactId> < /dependency> <dependency> <groupId>org.mybatis</groupId> <artifactid>mybatis-spring&lt ;/artifactid> <version>1.2.2</version> </dependency> <dependency> <groupid>org. mybatis</groupid> <artifactId>mybatis</artifactId> <version>3.2.8</version> </de pendency> <dependency> <groupId>mysql</groupId> <artifactid>mysql-connector-java</a rtifactid> </dependency> <dependency> <groupId>com.mchange</groupId> <artifactid& gt;c3p0</artifactid> <version>0.9.2.1</version> </dependency> </dependencies> < build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifact Id>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project> 


The project structure is as follows:



application.properties File:

#datasource
spring.datasource.jdbcurl=jdbc:mysql://115.28.92.178:3306/wms?useunicode\=true& characterencoding\=utf8;autoreconnect\=true;maxreconnects\=10;connecttimeout\=180000;sockettimeout\=180000
spring.datasource.user=root
spring.datasource.password=xxx
spring.datasource.driverclass= Com.mysql.jdbc.Driver
spring.datasource.maxactive=100
spring.datasource.initialpoolsize=5
Spring.datasource.minpoolsize=5
spring.datasource.maxpoolsize=20
spring.datasource.maxstatements=100
spring.datasource.maxidletime=3600
spring.datasource.acquireincrement=2
spring.datasource.acquireretryattempts=10
spring.datasource.acquireretrydelay=600
Spring.datasource.testconnectiononcheckin=true
spring.datasource.idleconnectiontestperiod=1200
spring.datasource.checkouttimeout=100000





Database (MySQL):

DROP TABLE IF EXISTS ' user ';
CREATE TABLE ' user ' (
  ' userId ' int (one) ' Not NULL  PRIMARY KEY auto_increment COMMENT "userid",
	' userName ' varchar (+) NOT null UNIQUE COMMENT "username",
	' password ' varchar ($) NOT null COMMENT "password",
  ' name ' varchar (+) NOT NULL COMM ENT "real name",
	' sex ' int default 0  COMMENT "gender",
	' tel ' varchar (full) default NULL COMMENT "Phone",
	' status ' int DE FAULT 0 COMMENT "status", 
	' Enable ' TINYINT (1) DEFAULT 1 COMMENT "Whether enabled",
	' createdtime ' datetime NOT NULL COMMENT ' when created ",
	' desc ' varchar (+) default null COMMENT" Remarks "
) engine=innodb default Charset=utf8;
ALTER table ' user ' comment= ' users table ';

INSERT into ' USER ' VALUES (1, ' admin ', ' admin ', ' Vic ', 1, ' 18700000000 ', 0,1,now (), ' System Manager ');

corresponding entity class User:

Package com.vic.entity;

Import java.util.Date;

/**
 * 
 * @author Vic
 * @desc entity for table (user) * */Public

class User {

	private int useri D;

	Private String userName;

	private String password;

	private String name;

	private int sex;

	Private String Tel;
	
	private int status;
	
	Private Boolean enable;
	
	Private Date createdtime;
	
	Private String desc;

	Getter setter ....
	

}


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>
	<typeAliases>
	    <typealias type= "Com.vic.entity.User" alias= "User"/ >
	</typeAliases>
</configuration>


Datasourceconfig.java:

Package com.vic.config;
Import Org.apache.ibatis.session.SqlSessionFactory;
Import Org.apache.log4j.Logger;
Import Org.mybatis.spring.SqlSessionFactoryBean;
Import Org.mybatis.spring.annotation.MapperScan;
Import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
Import org.springframework.boot.context.properties.ConfigurationProperties;
Import Org.springframework.context.annotation.Bean;
Import org.springframework.context.annotation.Configuration;
Import Org.springframework.core.io.support.PathMatchingResourcePatternResolver;

Import Org.springframework.jdbc.datasource.DataSourceTransactionManager;

Import Com.mchange.v2.c3p0.ComboPooledDataSource; 
/** * * @author Vic * @desc datasrouce config and mybatis Scan config * */@Configuration @EnableAutoConfiguration @MapperScan ("Com.vic.dao") public class Datasourceconfig {private static Logger Logger = Logger.getlogger (datasourcec

	Onfig.class); @Bean @ConfigurationProperties (prefix= "Spring.datasource") pUblic Combopooleddatasource DataSource () {return new Combopooleddatasource (); } @Bean Public Sqlsessionfactory Sqlsessionfactorybean () throws Exception {Sqlsessionfactorybean sqlsess
        Ionfactorybean = new Sqlsessionfactorybean ();
        Combopooleddatasource DataSource = DataSource ();
        Sqlsessionfactorybean.setdatasource (DataSource);
        Pathmatchingresourcepatternresolver resolver = new Pathmatchingresourcepatternresolver ();
        Sqlsessionfactorybean.setconfiglocation (Resolver.getresource ("Classpath:/mybatis-config.xml"));
        Sqlsessionfactorybean.setmapperlocations (Resolver.getresources ("Classpath:/mapper/*.xml"));
        Logger.info ("Sqlsessionfactory Bean init success.");
    return Sqlsessionfactorybean.getobject (); } @Bean Public Datasourcetransactionmanager TransactionManager () {return new Datasourcetransactionma
    Nager (DataSource ());
 }
   
}

Iuserdao and Usermapper.xml

Package Com.vic.dao;

Import java.util.List;

Import org.springframework.stereotype.Repository;

Import Com.vic.entity.User;

/**
 * 
 * @author Vic
 * @desc User Mapper Dao */
@Repository Public
interface Iuserdao {

	Public list<user> getAll ();
	
}


<?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.vic.dao.IUserDao" >
 
 	<resultmap type= "User" id= "Userresultmap" >
		<id property= "userid" column= "userid"/>
		<result property= "UserName" column= "UserName"/>
		<result property= "password" column= "password"/>
		<result property= "name" column= "name"/>
		<result property= "Sex" column= "sex"/>
		<result property= "Tel" column= "tel"/>
		<result property= "status" column= "status"/>
		<result property= "Enable" column= "Enable"/>
		<result property= "Createdtime "column=" Createdtime "/>
		<result property=" desc "column=" desc "/>
	</resultMap>
 	
 	
  < Select Id= "GetAll" resultmap= "Userresultmap" >
   		select * from ' user ';
  </select>
 
</mapper>

Test Controller,responsemodal:

Package Com.vic.controller;

Import java.util.List;

Import org.springframework.beans.factory.annotation.Autowired;
Import org.springframework.web.bind.annotation.RequestMapping;
Import Org.springframework.web.bind.annotation.RestController;

Import Com.vic.entity.User;
Import Com.vic.modal.ResponseModal;
Import Com.vic.service.IUserService;

@RestController public
class Examplecontroller {

	@Autowired
	private iuserservice userservice;
	
	@RequestMapping ("/users") public
	Responsemodal users () {
		list<user> users = Userservice.getall ();
		Responsemodal modal = new Responsemodal (200,true, "", users);
		return modal;
	}
	
}

Package com.vic.modal;

public class Modal {public
	

	Modal () {
		super ();
	}

	public Modal (int code, Boolean success, String message) {
		super ();
		This.code = code;
		this.success = success;
		this.message = message;
	}

	private int code;
	
	Private Boolean success;
	
	private String message;

	public int GetCode () {
		return code;
	}

	public void Setcode (int code) {
		this.code = code;
	}

	public Boolean issuccess () {
		return success;
	}

	public void Setsuccess (Boolean success) {
		this.success = success;
	}

	Public String GetMessage () {
		return message;
	}

	public void Setmessage (String message) {
		this.message = message;
	}
	
}



Package com.vic.modal;

Import java.io.Serializable;

public class Responsemodal extends Modal implements serializable{

	private static final long Serialversionuid = 1l;
  
   public Responsemodal () {
		super ();
	}
	
	Public responsemodal (int code,boolean success,string message) {
		super (code,success,message);
	}
	
	Public responsemodal (int code,boolean success,string message,object obj) {
		super (code,success,message);
		This.response = obj;
	}
	
	Private Object response;

	Public Object GetResponse () {
		return response;
	}

	public void Setresponse (Object response) {
		this.response = response;
	}
	
}

  

Application.java

Package Com.vic;

Import org.springframework.boot.SpringApplication;
Import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication public
class Application {public

	static void Main (string[] args) throws Exception {
		Springapplication application = new Springapplication (application.class);
		Application.Run (args);
	}
}


Run main, browser input localhost:8080/users


Sample code Download



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.