SpringCloud(第041編)Mysqlデータベースをリンクし、JdbcTemplateでデータベースアクセスを記述する


SpringCloud(第041編)Mysqlデータベースをリンクし、JdbcTemplateでデータベースアクセスを記述する
-
一、大まかに紹介する
1、       JPA       ,            JdbcTemplate       ;
2、  JdbcTemplate           ,      sql      ,     ;
3、        mysql     ,              ;

二、実現手順
2.1 mavenリファレンスパッケージの追加


    4.0.0

    springms-provider-user-mysql-jdbctemplate
    1.0-SNAPSHOT
    jar
    
    
        com.springms.cloud
        springms-spring-cloud
        1.0-SNAPSHOT
    
    
    
        
        
            org.springframework.boot
            spring-boot-starter-data-jpa
        

        
        
            org.springframework.boot
            spring-boot-starter-web
        

        
        
            mysql
            mysql-connector-java
        
    


2.2アプリケーションプロファイルの追加(springms-provider-user-mysql-j d b c t e m platesrcmainresourcesapplication.yml)
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
#####################################################################################################

2.3エンティティユーザークラスUser(springms-provider-user-mysql-jdbctemplate/src/main/java/com/springms/cloud/entity/User.java)の追加
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 + '\'' +
            '}';
  }
}

2.4エンティティアカウントクラスAccount(springms-provider-user-mysql-jdbctemplate/src/main/java/com/springms/cloud/entity/ACcount.java)の追加
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 +
                '}';
    }
}


2.5ユーザーDAOインタフェースの追加(springms-provider-user-mysql-jdbctemplate/src/main/java/com/springms/cloud/dao/InserDao.java)
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 findAllUsers();

    int insertUser(User user);
}

2.6アカウントDAOインタフェースの追加(springms-provider-user-mysql-jdbctemplate/src/main/java/com/springms/cloud/dao/AccountDao.java)
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 findAccountList();
}

2.7ユーザーDAOインタフェース実装クラスの追加(springms-provider-user-mysql-jdbctemplate/src/main/java/com/springms/cloud/dao/impl/UserDaoImpl.java)
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 rowMapper = new BeanPropertyRowMapper(User.class);

        // 3.       

        //List 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 findAllUsers(){
        // 1.     sql  
        String querySQL = "select * from user";

        // 2.     RowMapper
        RowMapper rowMapper = new BeanPropertyRowMapper(User.class);

        // 3.       
        List 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()});
    }
}

2.8アカウントDAOインタフェース実装クラスの追加(springms-provider-user-mysql-jdbctemplate/src/main/java/com/springms/cloud/dao/impl/accountDaoImpl.java)
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 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 findAccountList() {
        List list = jdbcTemplate.query("select * from account", new Object[]{}, new BeanPropertyRowMapper(Account.class));
        if(list!=null && list.size()>0){
            return list;
        }else{
            return null;
        }
    }
}

2.9ユーザー・サービス・インタフェースの追加(springms-provider-user-mysql-jdbctemplate/src/main/java/com/springms/cloud/service/InUserService.java)
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 findAllUsers();

    int insertUser(User user);
}

2.10アカウントサービスインタフェースの追加(springms-provider-user-mysql-jdbctemplate/src/main/java/com/springms/cloud/service/AccountService.java)
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 findAccountList();

}

2.11ユーザーサービスインタフェース実装クラスの追加(springms-provider-user-mysql-jdbctemplate/src/main/java/com/springms/cloud/service/impl/UserServiceImpl.java)
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 findAllUsers(){
        return userDao.findAllUsers();
    }

    @Override
    public int insertUser(User user) {
        return userDao.insertUser(user);
    }
}

2.12アカウントサービスインタフェース実装クラスの追加(springms-provider-user-mysql-jdbctemplate/src/main/java/com/springms/cloud/service/impl/accountServiceImpl.java)
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 findAccountList() {
        return accountDAO.findAccountList();
    }
}

2.13ユーザーWebアクセス層Controller(springms-provider-user-mysql-crudrepository/src/main/java/com/springms/cloud/controller/Provider/user-mysql-crudReporoller.java)の追加
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 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;
    }
}

2.14アカウントWebアクセス層Controller(springms-provider-user-mysql-crudepository/src/main/java/com/springms/cloud/controller/providerUserMysqlCrudReporoller.java)の追加
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 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";
        }
    }
}

2.15マイクロサービス起動クラス(springms-provider-user-mysql-crudrepository/src/main/java/com/springms/cloud/M s P r o v i derUserMysqlCrudRepoApplication.java)の追加
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       】】】】】】   .");
    }
}

三、テスト
/****************************************************************************************
  、      Mysql      (  JdbcTemplate      ):

 1、   springms-provider-user-mysql-jdbctemplate     ,  1   ;
 2、         http://localhost:8315/simplejdbc/6       ID=10           ;

 3、   IDEA      Test Restful WebService    HTTP POST   ,    username、age、balance    ,      ,   mysql            ,      mysql              :
 4、   REST Client    "/simplejdbc/list"   ,     mysql                 ;

 5、      http://localhost:8315/account/         ,           ;
 ****************************************************************************************/

四、ダウンロードアドレス
https://gitee.com/ylimhhmily/SpringCloudTutorial.git
SpringCloudTutorial交流QQ群:235322432
SpringCloudTutorial交流微信群:微信の疎通の群のQRコードのピクチャーのリンク
注目を歓迎して、あなたのはきっと私に対する最大の支持です!!!