一、前面章節提到了JPA操做訪問數據庫,本章節咱們講解一下如何用JdbcTemplate操做訪問數據庫; 二、使用JdbcTemplate是一個相對更底層的操做,能夠直接編寫sql語句操做數據,更具靈活性; 三、另外配置文件中的mysql數據庫配置,那麼就得你們本身用本身的了哈;
<?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> <artifactId>springms-provider-user-mysql-jdbctemplate</artifactId> <version>1.0-SNAPSHOT</version> <packaging>jar</packaging> <parent> <groupId>com.springms.cloud</groupId> <artifactId>springms-spring-cloud</artifactId> <version>1.0-SNAPSHOT</version> </parent> <dependencies> <!-- 訪問數據庫模塊 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <!-- web模塊 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- MYSQL --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> </dependencies> </project>
server: port: 8315 spring: application: name: springms-provider-user-mysql-jdbctemplate #所有小寫 ##################################################################################################### # mysql 屬性配置 datasource: driver-class-name: com.mysql.jdbc.Driver url: jdbc:mysql://ip:3306/hmilyylimh username: username password: password jpa: hibernate: #ddl-auto: create #ddl-auto:設爲create表示每次都從新建表 ddl-auto: update #ddl-auto:設爲update表示每次都不會從新建表 show-sql: true ##################################################################################################### ##################################################################################################### # 打印日誌 logging: level: root: INFO org.hibernate: INFO org.hibernate.type.descriptor.sql.BasicBinder: TRACE org.hibernate.type.descriptor.sql.BasicExtractor: TRACE com.springms: DEBUG #####################################################################################################
package com.springms.cloud.entity; public class User { private Long id; private String username; private String name; private Integer age; private String balance; public Long getId() { return this.id; } public void setId(Long id) { this.id = id; } public String getUsername() { return this.username; } public void setUsername(String username) { this.username = username; } public String getName() { return this.name; } public void setName(String name) { this.name = name; } public Integer getAge() { return this.age; } public void setAge(Integer age) { this.age = age; } public String getBalance() { return this.balance; } public void setBalance(String balance) { this.balance = balance; } @Override public String toString() { return "User{" + "id=" + id + ", username='" + username + '\'' + ", name='" + name + '\'' + ", age=" + age + ", balance='" + balance + '\'' + '}'; } }
package com.springms.cloud.entity; public class Account { private int id ; private String name ; private double money; 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 double getMoney() { return money; } public void setMoney(double money) { this.money = money; } @Override public String toString() { return "Account{" + "id=" + id + ", name='" + name + '\'' + ", money=" + money + '}'; } }
package com.springms.cloud.dao; import com.springms.cloud.entity.User; import java.util.List; /** * 簡單用戶連接Mysql數據庫微服務(經過@Repository註解標註該類爲持久化操做對象)。 * * @author hmilyylimh * * @version 0.0.1 * * @date 17/10/18 * */ public interface IUserDao { User findUserById(Long id); List<User> findAllUsers(); int insertUser(User user); }
package com.springms.cloud.dao; import com.springms.cloud.entity.Account; import java.util.List; public interface IAccountDao { int add(Account account); int update(Account account); int delete(int id); Account findAccountById(int id); List<Account> findAccountList(); }
package com.springms.cloud.dao.impl; import com.springms.cloud.dao.IUserDao; import com.springms.cloud.entity.User; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.BeanPropertyRowMapper; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.RowMapper; import org.springframework.stereotype.Repository; import java.util.List; /** * 簡單用戶連接Mysql數據庫微服務(經過@Repository註解標註該類爲持久化操做對象)。 * * @author hmilyylimh * * @version 0.0.1 * * @date 17/10/18 * */ @Repository public class UserDaoImpl implements IUserDao { /** * 經過@Resource註解引入JdbcTemplate對象。 */ @Autowired private JdbcTemplate jdbcTemplate; //@Transactional(readOnly = true) @Override public User findUserById(Long id){ // 1. 定義一個sql語句 String querySQL = "select * from user where id = ?"; // 2. 定義一個RowMapper RowMapper<User> rowMapper = new BeanPropertyRowMapper<User>(User.class); // 3. 執行查詢方法 //List<User> list = jdbcTemplate.query("select * from account where id = ?", new Object[]{id}, new BeanPropertyRowMapper(User.class)); User user = jdbcTemplate.queryForObject(querySQL, new Object[]{id}, rowMapper); return user; } //@Transactional(readOnly = true) @Override public List<User> findAllUsers(){ // 1. 定義一個sql語句 String querySQL = "select * from user"; // 2. 定義一個RowMapper RowMapper<User> rowMapper = new BeanPropertyRowMapper<User>(User.class); // 3. 執行查詢方法 List<User> users = jdbcTemplate.query(querySQL, new Object[]{}, rowMapper); return users; } @Override public int insertUser(User user) { // 1. 定義一個sql語句 String execSQL = "INSERT into user (username, name, age, balance) values (?, ?, ?, ?)"; // 2. 執行查詢方法 return jdbcTemplate.update(execSQL, new Object[]{user.getUsername(), user.getName(), user.getAge(), user.getBalance()}); } }
package com.springms.cloud.dao.impl; import com.springms.cloud.dao.IAccountDao; import com.springms.cloud.entity.Account; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.BeanPropertyRowMapper; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Repository; import java.util.List; @Repository public class AccountDaoImpl implements IAccountDao { @Autowired private JdbcTemplate jdbcTemplate; @Override public int add(Account account) { return jdbcTemplate.update("insert into account(name, money) values(?, ?)", account.getName(),account.getMoney()); } @Override public int update(Account account) { return jdbcTemplate.update("UPDATE account SET NAME=? ,money=? WHERE id=?", account.getName(),account.getMoney(),account.getId()); } @Override public int delete(int id) { return jdbcTemplate.update("DELETE from TABLE account where id=?",id); } @Override public Account findAccountById(int id) { List<Account> list = jdbcTemplate.query("select * from account where id = ?", new Object[]{id}, new BeanPropertyRowMapper(Account.class)); if(list!=null && list.size()>0){ Account account = list.get(0); return account; }else{ return null; } } @Override public List<Account> findAccountList() { List<Account> list = jdbcTemplate.query("select * from account", new Object[]{}, new BeanPropertyRowMapper(Account.class)); if(list!=null && list.size()>0){ return list; }else{ return null; } } }
package com.springms.cloud.service; import com.springms.cloud.entity.User; import java.util.List; /** * 簡單用戶連接Mysql數據庫微服務(經過@Service註解標註該類爲持久化操做對象)。 * * @author hmilyylimh * * @version 0.0.1 * * @date 17/10/18 * */ public interface IUserService { User findUserById(Long id); List<User> findAllUsers(); int insertUser(User user); }
package com.springms.cloud.service; import com.springms.cloud.entity.Account; import java.util.List; public interface IAccountService { int add(Account account); int update(Account account); int delete(int id); Account findAccountById(int id); List<Account> findAccountList(); }
package com.springms.cloud.service.impl; import com.springms.cloud.dao.IUserDao; import com.springms.cloud.entity.User; import com.springms.cloud.service.IUserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; /** * 簡單用戶連接Mysql數據庫微服務(經過@Service註解標註該類爲持久化操做對象)。 * * @author hmilyylimh * * @version 0.0.1 * * @date 17/10/18 * */ @Service public class UserServiceImpl implements IUserService { @Autowired private IUserDao userDao; @Override public User findUserById(Long id){ return userDao.findUserById(id); } @Override public List<User> findAllUsers(){ return userDao.findAllUsers(); } @Override public int insertUser(User user) { return userDao.insertUser(user); } }
package com.springms.cloud.service.impl; import com.springms.cloud.dao.IAccountDao; import com.springms.cloud.entity.Account; import com.springms.cloud.service.IAccountService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; @Service public class AccountServiceImpl implements IAccountService { @Autowired IAccountDao accountDAO; @Override public int add(Account account) { return accountDAO.add(account); } @Override public int update(Account account) { return accountDAO.update(account); } @Override public int delete(int id) { return accountDAO.delete(id); } @Override public Account findAccountById(int id) { return accountDAO.findAccountById(id); } @Override public List<Account> findAccountList() { return accountDAO.findAccountList(); } }
package com.springms.cloud.controller; import com.springms.cloud.service.IUserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import com.springms.cloud.entity.User; import java.util.List; /** * 用戶微服務Controller。 * * @author hmilyylimh * * @version 0.0.1 * * @date 17/10/18 * */ @RestController public class ProviderUserMysqlJdbcController { @Autowired private IUserService userService; @GetMapping("/simplejdbc/{id}") public User findUserById(@PathVariable Long id) { return this.userService.findUserById(id); } @GetMapping("/simplejdbc/list") public List<User> findAllUsers() { return this.userService.findAllUsers(); } /** * 添加一個student,使用postMapping接收post請求 * * http://localhost:8315/simple/addUser?username=user11&age=11&balance=11 * * @return */ @PostMapping("/simplejdbc/addUser") public User insertUser(@RequestParam(value = "username", required=false) String username, @RequestParam(value = "age", required=false) Integer age, @RequestParam(value = "balance", required=false) String balance){ User user=new User(); user.setUsername(username); user.setName(username); user.setAge(age); user.setBalance(balance); int result = userService.insertUser(user); if(result > 0){ return user; } user.setId(0L); user.setName(null); user.setUsername(null); user.setBalance(null); return user; } }
package com.springms.cloud.controller; import com.springms.cloud.entity.Account; import com.springms.cloud.service.IAccountService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.List; @RestController @RequestMapping("/account") public class AccountController { @Autowired IAccountService accountService; @RequestMapping(value = "/list",method = RequestMethod.GET) public List<Account> getAccounts(){ return accountService.findAccountList(); } @RequestMapping(value = "/{id}",method = RequestMethod.GET) public Account getAccountById(@PathVariable("id") int id){ return accountService.findAccountById(id); } @RequestMapping(value = "/{id}",method = RequestMethod.PUT) public String updateAccount(@PathVariable("id")int id , @RequestParam(value = "name",required = true)String name, @RequestParam(value = "money" ,required = true)double money){ Account account=new Account(); account.setMoney(money); account.setName(name); account.setId(id); int t=accountService.update(account); if(t==1){ return account.toString(); }else { return "fail"; } } @RequestMapping(value = "",method = RequestMethod.POST) public String postAccount( @RequestParam(value = "name")String name, @RequestParam(value = "money" )double money){ Account account=new Account(); account.setMoney(money); account.setName(name); int t= accountService.add(account); if(t==1){ return account.toString(); }else { return "fail"; } } }
package com.springms.cloud; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; /** * 連接Mysql數據庫,經過JdbcTemplate編寫數據庫訪問。 * * @author hmilyylimh * * @version 0.0.1 * * @date 17/10/18 * */ @SpringBootApplication public class MsProviderUserMysqlJdbcApplication { public static void main(String[] args) { SpringApplication.run(MsProviderUserMysqlJdbcApplication.class, args); System.out.println("【【【【【【 連接MysqlJdbc數據庫微服務 】】】】】】已啓動."); } }
/**************************************************************************************** 1、簡單用戶連接Mysql數據庫微服務(經過JdbcTemplate編寫數據訪問): 一、啓動 springms-provider-user-mysql-jdbctemplate 模塊服務,啓動1個端口; 二、在瀏覽器輸入地址 http://localhost:8315/simplejdbc/6 能夠看到用戶ID=10的信息成功的被打印出來; 三、使用 IDEA 自帶工具 Test Restful WebService 發送 HTTP POST 請求,並添加 username、age、balance三個參數,而後執行請求,並去 mysql 數據庫查看數據是否存在,正常狀況下 mysql 數據庫剛剛插入的數據成功了: 四、使用 REST Client 執行 "/simplejdbc/list" 接口,也正常將 mysql 數據庫中全部的用戶信息打印出來了; 五、而後再操做 http://localhost:8315/account/ 該連接的接口操做,也是能夠正常操做訪問的; ****************************************************************************************/
https://gitee.com/ylimhhmily/SpringCloudTutorial.gitjava
SpringCloudTutorial交流QQ羣: 235322432mysql
SpringCloudTutorial交流微信羣: 微信溝通羣二維碼圖片連接git
歡迎關注,您的確定是對我最大的支持!!!web