别人推荐的两篇blog,
Springboot 整合 Mybatis 的完整 Web 案例
社区 Spring Boot 从入门到进阶系列教程
创建项目
使用Intellij直接new一个新项目
1、项目结构介绍
com.zuo.controller - Controller 层
com.zuo.dao - 数据操作层 DAO
com.zuo.domain - 实体类
com.zuo.service - 业务逻辑层
DemoApplication - 应用启动类
application.properties - 应用配置文件,应用启动会自动读取配置
- 整个工程的
pom.xml
新建项目生成都pom.xml
4.0.0
com.zuo
demo
0.0.1-SNAPSHOT
jar
demo
Demo project for Spring Boot
org.springframework.boot
spring-boot-starter-parent
2.0.3.RELEASE
UTF-8
UTF-8
1.8
org.springframework.boot
spring-boot-starter
org.springframework.boot
spring-boot-starter-test
test
org.springframework.boot
spring-boot-maven-plugin
我们还可以根据需要引入下面都依赖
org.springframework.boot
spring-boot-starter-web
junit
junit
4.12
org.mybatis.spring.boot
mybatis-spring-boot-starter
${mybatis-spring-boot}
mysql
mysql-connector-java
${mysql-connector}
com.alibaba
fastjson
1.2.32
2、改数据库配置
打开 application.properties 文件, 修改相应的数据源配置,比如数据源地址、账号、密码等。(如果不是用 MySQL,自行添加连接驱动 pom,然后修改驱动名配置。)
比如我们在移动端常用端SQLite数据库的连接
org.xerial
sqlite-jdbc
3.21.0.1
3、写个Controller
类
Spring4可以使用 @RestController
在Spring4之前都版本需要@Controller @ResponseBody结合使用
@RestController和@RequestMapping注解是来自SpringMVC的注解,它们不是SpringBoot的特定部分。
- @RestController:提供实现了REST API,可以服务JSON,XML或者其他。这里是以String的形式渲染出结果。
- @RequestMapping:提供路由信息,"/“路径的HTTP Request都会被映射到sayHello方法进行处理。
- 写一个测试都请求类
/**
* Spring Boot demo案例
*
* @author zuo
* @date 2018/7/29 12:56
*/
@Controller
@ResponseBody
public class TestController {
@RequestMapping("/login")
public String login() {
return "{\"userid\":1,\"userName\":\"lihua\"}";
}
}
4、模拟请求
运行DemoApplication
待控制台出现如下信息,即表示程序启动成功了,我们就可以 http://localhost:8080/login进行访问
连接数据库
SpringBoot连接SQLite数据库(基于Spring-Data-Jpa和Gradle配置)
Spring整合Hibernate详细步骤
由于我之前把数据存在移动端的sqlite数据库中,所以这里我就连接了Sqlite数据库了。
1、加上sqlite依赖
org.xerial
sqlite-jdbc
3.21.0.1
2、配置application.properties
#配置sqlite数据库连接方式
spring.datasource.url=jdbc:sqlite:D://zuoDbFile//task.db
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=org.sqlite.JDBC
#mybatis配置信息
mybatis.typeAliasesPackage=com.zuo.bean
mybatis.mapperLocations=classpath:mappers/*.xml
#sqlite自己配置Hibernate连接
spring.jpa.database-platform=com.zuo.sqlite.SQLiteDialect
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
Spring-Data-Jpa采用Hibernate来关联数据库,而Hibernate想要支持SQLite,需要自己配置连接,代码如上
3、SQLiteDialect
/**
* $desc$
*
* @author zuo
* @date 2018/7/29 20:44
*/
public class SQLiteDialect extends Dialect {
public SQLiteDialect() {
registerColumnType(Types.BIT, "integer");
registerColumnType(Types.TINYINT, "tinyint");
registerColumnType(Types.SMALLINT, "smallint");
registerColumnType(Types.INTEGER, "integer");
registerColumnType(Types.BIGINT, "bigint");
registerColumnType(Types.FLOAT, "float");
registerColumnType(Types.REAL, "real");
registerColumnType(Types.DOUBLE, "double");
registerColumnType(Types.NUMERIC, "numeric");
registerColumnType(Types.DECIMAL, "decimal");
registerColumnType(Types.CHAR, "char");
registerColumnType(Types.VARCHAR, "varchar");
registerColumnType(Types.LONGVARCHAR, "longvarchar");
registerColumnType(Types.DATE, "date");
registerColumnType(Types.TIME, "time");
registerColumnType(Types.TIMESTAMP, "timestamp");
registerColumnType(Types.BINARY, "blob");
registerColumnType(Types.VARBINARY, "blob");
registerColumnType(Types.LONGVARBINARY, "blob");
// registerColumnType(Types.NULL, "null");
registerColumnType(Types.BLOB, "blob");
registerColumnType(Types.CLOB, "clob");
registerColumnType(Types.BOOLEAN, "integer");
registerFunction( "concat", new VarArgsSQLFunction(StringType.INSTANCE, "", "||", "") );
registerFunction( "mod", new SQLFunctionTemplate( StringType.INSTANCE, "?1 % ?2" ) );
registerFunction( "substr", new StandardSQLFunction("substr", StringType.INSTANCE) );
registerFunction( "substring", new StandardSQLFunction( "substr", StringType.INSTANCE) );
}
public boolean supportsIdentityColumns() {
return true;
}
/*
public boolean supportsInsertSelectIdentity() {
return true; // As specify in NHibernate dialect
}
*/
public boolean hasDataTypeInIdentityColumn() {
return false; // As specify in NHibernate dialect
}
/*
public String appendIdentitySelectToInsert(String insertString) {
return new StringBuffer(insertString.length()+30). // As specify in NHibernate dialect
append(insertString).
append("; ").append(getIdentitySelectString()).
toString();
}
*/
public String getIdentityColumnString() {
// return "integer primary key autoincrement";
return "integer";
}
public String getIdentitySelectString() {
return "select last_insert_rowid()";
}
public boolean supportsLimit() {
return true;
}
protected String getLimitString(String query, boolean hasOffset) {
return new StringBuffer(query.length()+20).
append(query).
append(hasOffset ? " limit ? offset ?" : " limit ?").
toString();
}
public boolean supportsTemporaryTables() {
return true;
}
public String getCreateTemporaryTableString() {
return "create temporary table if not exists";
}
public boolean dropTemporaryTableAfterUse() {
return false;
}
public boolean supportsCurrentTimestampSelection() {
return true;
}
public boolean isCurrentTimestampSelectStringCallable() {
return false;
}
public String getCurrentTimestampSelectString() {
return "select current_timestamp";
}
public boolean supportsUnionAll() {
return true;
}
public boolean hasAlterTable() {
return false; // As specify in NHibernate dialect
}
public boolean dropConstraints() {
return false;
}
public String getAddColumnString() {
return "add column";
}
public String getForUpdateString() {
return "";
}
public boolean supportsOuterJoinForUpdate() {
return false;
}
public String getDropForeignKeyString() {
throw new UnsupportedOperationException("No drop foreign key syntax supported by SQLiteDialect");
}
public String getAddForeignKeyConstraintString(String constraintName,
String[] foreignKey, String referencedTable, String[] primaryKey,
boolean referencesPrimaryKey) {
throw new UnsupportedOperationException("No add foreign key syntax supported by SQLiteDialect");
}
public String getAddPrimaryKeyConstraintString(String constraintName) {
throw new UnsupportedOperationException("No add primary key syntax supported by SQLiteDialect");
}
public boolean supportsIfExistsBeforeTableName() {
return true;
}
public boolean supportsCascadeDelete() {
return false;
}
}
4、定义用户实体类
/**
* 用户信息实体
* author: zuo
* date: 2017/12/7 16:51
*/
public class UserBean {
public int userId; //用户编号
public String userName; //用户名称
public String loginName; //登录名
public String password; //密码
public String org; //部门名称
public String group; //班组类别
public String groupName; //班组名称
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getLoginName() {
return loginName;
}
public void setLoginName(String loginName) {
this.loginName = loginName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getOrg() {
return org;
}
public void setOrg(String org) {
this.org = org;
}
public String getGroup() {
return group;
}
public void setGroup(String group) {
this.group = group;
}
public String getGroupName() {
return groupName;
}
public void setGroupName(String groupName) {
this.groupName = groupName;
}
}
5、定义Dao
/**
* 用户表查询
*
* @author zuo
* @date 2018/7/29 19:48
*/
@Mapper
@Component
public interface UserDao {
UserBean findUser(UserBean userBean);
}
6、接口查询
/**
* Spring Boot demo案例
*
* @author zuo
* @date 2018/7/29 12:56
*/
@Controller
@ResponseBody
@RequestMapping("/user")
public class UserController {
@Autowired
private UserDao userDao;
@RequestMapping("/login")
@ResponseBody
public MsgBean login(HttpServletRequest request, UserBean userBean) {
List list = new ArrayList<>();
UserBean user = userDao.findUser(userBean);
MsgBean msgBean = new MsgBean();
if (user != null) {
list.add(user);
msgBean.setCode(BaseConfig.SUCCESSCODE);
msgBean.setMsg(BaseConfig.SUCCESSMSG);
msgBean.setData(user);
} else {
msgBean.setCode(BaseConfig.ERRRORCODE);
msgBean.setMsg(BaseConfig.ERRRORMSG);
}
return msgBean;
}
}
7、基础配置文件
- 公用的状态码等属性
/**
* 定义一些公用属性
*
* @author zuo
* @date 2018/7/29 21:12
*/
public interface BaseConfig {
//请求成功
int SUCCESSCODE = 1;
String SUCCESSMSG = "请求成功";
//请求失败
int ERRRORCODE = -1;
String ERRRORMSG = "请求失败";
}
- 公用的接口数据返回类
/**
* 公用的接口请求返回类
*
* @author zuo
* @date 2018/7/29 21:08
*/
public class MsgBean {
private int code;
private String msg;
private Object data;
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
}