springboot集成mybatis实例代码

网友投稿 206 2023-05-22


springboot集成mybatis实例代码

springboot如何配置web项目请参考前一章,在此基础上集成mybatis。

在pom文件中添加mybatis的依赖:

org.mybatis.spring.boot

mybatis-spring-boot-starter

1.2.0

添加mysql驱动:

mysql

mysql-connector-java

添加druid和fastjson依赖,http://使用阿里巴巴druid连接池

com.alibaba

druid

1.0.28

com.alibaba

fastjson

1.2.30

配置数据源,在application.yml中:

spring:

datasource:

name: test

url: jdbc:mysql://127.0.0.1:3306/test

username: root

pasrSOwPAEjnsword: 111111

# 使用druid数据源

type: com.alibaba.druid.pool.DruidDataSource

driver-class-name: com.mysql.jdbc.Driver

filters: stat

maxActive: 20

initialSize: 1

maxWait: 60000

minIdle: 1

timeBetweenEvictionRunsMillis: 60000

minEvictableIdleTimeMillis: 300000

validationQuery: select 'x'

testWhileIdle: true

testOnBorrow: false

testOnReturn: false

poolPreparedStatements: true

maxOpenPreparedStatements: 20

设置mybatis的mapper和model扫描路径:

mybatis:

mapperLocations: classpath:mapper/*.xml

typeAliasesPackage: com.yingxinhuitong.demo.model

#更多配置请参见:http://mybatis.org/spring-boot-starter/mybatis-spring-boot-autoconfigure/

接下来我们新建userMapper.xml,UserEntity以及UserDao:

UserEntity.class

package com.yingxinhuitong.demo.model;

/**

* Created by jack on 2017/4/20.

*/

public class UserEntity {

private Long id;

private String username;

private String password;

public Long getId() {

return id;

}

public void setId(Long 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;

}

}

UserDao

package com.yingxinhuitong.demo.dao;

import com.yingxinhuitong.demo.model.UserEntity;

import org.apache.ibatis.annotations.Mapper;

import java.util.List;

/**

* Created by jack on 2017/4/20.

*/

@Mapper

public interface UserDao {

List searchAll();

}

UserMapper.xml

select * from tab_user

创建一个控制器,注入UserDao,测试一下可不可以查询数据了:

@RestController

public class TestController {

@Resource

UserDao userDao;

@RequestMapping("/getusers")

public String test() {

List users = userDao.searchAll();

String usersJson = JSON.toJSONString(users);

return usersJson;

}

}

运行Application.class,启动成功后访问:http://localhost:9000/demo/getusers,输出内容如下:

复制代码 代码如下:

[{"id":1,"password":"000000","username":"test"},{"id":2,"password":"111111","username":"test1"},{"id":3,"password":"222222","username":"test2"}]

至此,springboot已完成对mybatis的集成。


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:struts1实现简单的登录功能实例(附源码)
下一篇:Java追加文件内容的三种方法实例代码
相关文章

 发表评论

暂时没有评论,来抢沙发吧~