springboot搭建mybatis配置文件版----连接mysql

一,创建项目

springboot搭建mybatis配置文件版----连接mysql_第1张图片

    创建一个springboot项目,使用Gradle依赖,添加的依赖为:

compile('org.mybatis.spring.boot:mybatis-spring-boot-starter:1.3.2')
	runtime('mysql:mysql-connector-java')
	// https://mvnrepository.com/artifact/com.alibaba/druid
	compile group: 'com.alibaba', name: 'druid', version: '1.1.9'

二,配置文件

           yml:

server:
  port: 8080
  
mybatis:
  mapper-locations: classpath:/mybatis/mapper/*.xml 
  config-location: classpath:/mybatis/mybatis-config.xml
  
spring:
  datasource:
    url: jdbc:mysql://localhost:3306/db_mybatis
    username: root
    password: root
    driver-class-name: com.mysql.jdbc.Driver
    # 使用druid数据源
    type: com.alibaba.druid.pool.DruidDataSource
         mybatis-config.xml:
  



    
    
             mapper.xml:



    
        
        
        
        
    


    





三,数据库设计

       
CREATE TABLE `tb_user` (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'ID',
  `username` varchar(50) NOT NULL COMMENT '用户名',
  `age` int(11) NOT NULL COMMENT '年龄',
  `ctm` datetime NOT NULL COMMENT '创建时间',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;


四,代码书写

       entity:

         需要生成getter和setter方法,无参构造器和有参构造器,也可以生成toString方法

import java.util.Date;


private int id;
private String username;
private int age;
private Date ctm;

       dao:

        通过id来查询用户信息,需加注解@Mapper


@Mapper
public interface UserDao {
    User getByPrimaryKey(@Param("id")Integer id);
}

       service:   

 

要点:1.类上面要加@Service        

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import com.meng.entity.User;
import com.meng.mapper.UserMapper;


@Service
public class UserService{

	@Resource
	private UserMapper userMapper;

	public User getByPrimaryKey(Integer id) {
		return userMapper.getUserById(id);
	}
}

       controller:

   采用Rest风格返回json数据

@RestController
public class UserController {
	
	@Autowired
	private UserService uService;
	
	@RequestMapping("/getUser")
	public User getUser() {
		
		User u = uService.getUserById(1);
		return u;
	}
}

 五,成功效果

         springboot搭建mybatis配置文件版----连接mysql_第2张图片

     

       

    


    

你可能感兴趣的:(#,springboot,JavaWeb)