Spring Boot实战之Rest接口开发及数据库基本操作


本文源码下载:

http://download.csdn.net/detail/sun_t89/9576427


1、修改pom.xml,添加依赖库,本文使用的是mysql

               

 <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>



2、修改配置文件application.properties,配置数据源及java持久层API相关信息

spring.datasource.url = jdbc:mysql://127.0.0.1:3306/springlearn
spring.datasource.username = root
spring.datasource.password = root
spring.datasource.driverClassName = com.mysql.jdbc.Driver


# 配置数据库
spring.jpa.database = MYSQL
# 查询时是否显示日志
spring.jpa.show-sql = true
# Hibernate ddl auto (create, create-drop, update)
spring.jpa.hibernate.ddl-auto = update
# Naming strategy
spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy
# stripped before adding them to the entity manager)
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect



3、添加数据模型 UserInfo.java

package com.xiaofangtech.sunt.bean;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;

@Entity
@Table(name="t_user")
public class UserInfo {
	@Id
	@GeneratedValue(strategy = GenerationType.AUTO)
	private int id;
	@NotNull
	private String name;
	
	private String password;
	
	private String salt;
	
	private String role;

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getSalt() {
		return salt;
	}

	public void setSalt(String salt) {
		this.salt = salt;
	}

	public String getRole() {
		return role;
	}

	public void setRole(String role) {
		this.role = role;
	}
}


4、添加数据访问接口类 UserInfoRepository.java

package com.xiaofangtech.sunt.repository;

import java.util.List;

import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;

import com.xiaofangtech.sunt.bean.UserInfo;

public interface UserInfoRepository extends CrudRepository<UserInfo, Integer>{
	UserInfo findUserInfoById(int id);
	List<UserInfo> findUserInfoByRole(String role);
	
	@Query(value = "select * from t_user limit ?1", nativeQuery =true)
	List<UserInfo> findAllUsersByCount(int count);
}


5、添加UserController.java,添加用户信息的增删改查操作

package com.xiaofangtech.sunt.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.xiaofangtech.sunt.bean.UserInfo;
import com.xiaofangtech.sunt.repository.UserInfoRepository;
import com.xiaofangtech.sunt.utils.ResultMsg;
import com.xiaofangtech.sunt.utils.ResultStatusCode;

@RestController
@RequestMapping("user")
public class UserController {
	@Autowired
	private UserInfoRepository userRepositoy;
	
	@RequestMapping("getuser")
	public Object getUser(int id)
	{
		UserInfo userEntity = userRepositoy.findUserInfoById(id);
		ResultMsg resultMsg = new ResultMsg(ResultStatusCode.OK.getErrcode(), ResultStatusCode.OK.getErrmsg(), userEntity);
		return resultMsg;
	}
	
	@RequestMapping("getusers")
	public Object getUsers(String role)
	{
		List<UserInfo> userEntities = userRepositoy.findUserInfoByRole(role);
		ResultMsg resultMsg = new ResultMsg(ResultStatusCode.OK.getErrcode(), ResultStatusCode.OK.getErrmsg(), userEntities);
		return resultMsg;
	}
	
	@Modifying
	@RequestMapping("adduser")
	public Object addUser(@RequestBody UserInfo userEntity)
	{
		userRepositoy.save(userEntity);
		ResultMsg resultMsg = new ResultMsg(ResultStatusCode.OK.getErrcode(), ResultStatusCode.OK.getErrmsg(), userEntity);
		return resultMsg;
	}
	
	@Modifying
	@RequestMapping("updateuser")
	public Object updateUser(@RequestBody UserInfo userEntity)
	{
		UserInfo user = userRepositoy.findUserInfoById(userEntity.getId());
		if (user != null)
		{
			user.setName(userEntity.getName());
			userRepositoy.save(user);
		}
		ResultMsg resultMsg = new ResultMsg(ResultStatusCode.OK.getErrcode(), ResultStatusCode.OK.getErrmsg(), null);
		return resultMsg;
	}
	
	@Modifying
	@RequestMapping("deleteuser")
	public Object deleteUser(int id)
	{
		userRepositoy.delete(id);
		ResultMsg resultMsg = new ResultMsg(ResultStatusCode.OK.getErrcode(), ResultStatusCode.OK.getErrmsg(), null);
		return resultMsg;
	}
}


6、封装返回的结果

添加ResultMsg.java

package com.xiaofangtech.sunt.utils;

public class ResultMsg {
	private int errcode;
	private String errmsg;
	private Object p2pdata;
	
	public ResultMsg(int ErrCode, String ErrMsg, Object P2pData)
	{
		this.errcode = ErrCode;
		this.errmsg = ErrMsg;
		this.p2pdata = P2pData;
	}
	public int getErrcode() {
		return errcode;
	}
	public void setErrcode(int errcode) {
		this.errcode = errcode;
	}
	public String getErrmsg() {
		return errmsg;
	}
	public void setErrmsg(String errmsg) {
		this.errmsg = errmsg;
	}
	public Object getP2pdata() {
		return p2pdata;
	}
	public void setP2pdata(Object p2pdata) {
		this.p2pdata = p2pdata;
	}
}


添加枚举类 ResultStatusCode.java

package com.xiaofangtech.sunt.utils;

public enum ResultStatusCode {
	OK(0, "OK"),
	SYSTEM_ERR(30001, "System error");
	
	private int errcode;
	private String errmsg;
	public int getErrcode() {
		return errcode;
	}

	public void setErrcode(int errcode) {
		this.errcode = errcode;
	}

	public String getErrmsg() {
		return errmsg;
	}

	public void setErrmsg(String errmsg) {
		this.errmsg = errmsg;
	}
	private ResultStatusCode(int Errode, String ErrMsg)
	{
		this.errcode = Errode;
		this.errmsg = ErrMsg;
	}
}

7、工程整体结构



8、运行测试,本文中测试使用的是user表,其中包含一些密码等信息未做处理,这个读者自行进行JsonIgnore处理

提供以下5个接口

http://localhost:8080/user/adduser

http://localhost:8080/user/updateuser

http://localhost:8080/user/getuser?id=13

http://localhost:8080/user/getusers?role=Manager

http://localhost:8080/user/deleteuser?id=13


测试运行结果

adduser接口




updateuser接口




getuser接口





9、调用以上接口时执行数据库操作时,会在内部转化为以下SQL语句

Hibernate: insert into t_user (name, password, role, salt) values (?, ?, ?, ?)


Hibernate: select userinfo0_.id as id1_0_, userinfo0_.name as name2_0_, userinfo0_.password as password3_0_, userinfo0_.role as role4_0_, userinfo0_.salt as salt5_0_ from t_user userinfo0_ where userinfo0_.id=?
Hibernate: update t_user set name=?, password=?, role=?, salt=? where id=?


Hibernate: select userinfo0_.id as id1_0_, userinfo0_.name as name2_0_, userinfo0_.password as password3_0_, userinfo0_.role as role4_0_, userinfo0_.salt as salt5_0_ from t_user userinfo0_ where userinfo0_.id=?


Hibernate: select userinfo0_.id as id1_0_, userinfo0_.name as name2_0_, userinfo0_.password as password3_0_, userinfo0_.role as role4_0_, userinfo0_.salt as salt5_0_ from t_user userinfo0_ where userinfo0_.role=?


Hibernate: select userinfo0_.id as id1_0_0_, userinfo0_.name as name2_0_0_, userinfo0_.password as password3_0_0_, userinfo0_.role as role4_0_0_, userinfo0_.salt as salt5_0_0_ from t_user userinfo0_ where userinfo0_.id=?
Hibernate: delete from t_user where id=?


10、数据库操作

JPA模块支持将查询字符串定义在方法名称中

如上例中

根据id值查询UserInfo实例

UserInfo findUserInfoById(int id);

根据role查询UserInfo实例
List<UserInfo> findUserInfoByRole(String role);


也可以直接使用原生的数据库语句

如下使用@Query注解

@Query(value = "select * from t_user limit ?1", nativeQuery =true)
List<UserInfo> findAllUsersByCount(int count);


11、在方法名中添加查询字符串参考



Logo

更多推荐