javaweb各類框架組合案例(七):springboot+jdbcTemplete+通用dao+restful

1、介紹java

1.springboot是spring項目的總結+整合mysql

  當咱們搭smm,ssh,ssjdbc等組合框架時,各類配置不勝其煩,不只是配置問題,在添加各類依賴時也是讓人頭疼,關鍵有些jar包之間還會出現衝突,讓你的項目出現難以解決的問題。基於這種狀況,springboot橫空出世,在考慮到Struts控制層框架有漏洞,springboot放棄(大多數企業一樣如此)了Struts,轉而代之是springMVC,不過,springboot是自動集成springMVC的,不須要任何配置,不須要任何依賴,直接使用各類控制層註解。springboot是springcloud的基礎,是開啓微服務時代的鑰匙。web

 

2、新建springboot工程spring

1. 使用idea2019新建project,選擇spring Initializr,nextsql

 

 2. 填寫座標信息,next數據庫

 

 3. Developer Tools選擇Lombok, Web選擇Spring Web Starter,SQL選擇JDBC API、MySQL Driver,nextspringboot

lombok是爲了省去實體類中getter/setter方法,使之在運行時動態添加getter/setterapp

 

4. 填寫項目名已經存放位置,finish框架

 

3、項目構建ssh

1. 數據庫準備(兩張表,分別是user用戶表和phone手機表,且是一對多關係)

create database ssdj;

CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`password` varchar(255) DEFAULT NULL,
`username` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;

CREATE TABLE `phone` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `brand` varchar(255) DEFAULT NULL,
  `user_id` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `FK_8t3jhwmmlxpq3qcwcy1a3alts` (`user_id`),
  CONSTRAINT `FK_8t3jhwmmlxpq3qcwcy1a3alts` FOREIGN KEY (`user_id`) REFERENCES `user` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;

insert into user(username,password) values(1001,123);

insert into phone(brand,user_id) values ('華爲',1),('iphone',1);

 

 2. pom.xml(不用動,默認)

 

3. 配置文件

  application.properties

spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/ssdj?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=GMT
spring.datasource.username=root
spring.datasource.password=root

  數據庫鏈接要添加時區,不然可能會報錯 

 

4.項目包結構

  分紅util、core、entity、dao、service、controller等結構包

 

5. 須要一個SqlFactory工具類來製造動態SQL語句

package club.xcreeper.springboot_jdbctemplete.util;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class SqlFactory {

    private String tableName;
    
    public Object[] params;
    
    public SqlFactory(Class<?> clazz) {
        tableName = clazz.getSimpleName().toLowerCase();
    }
    
    private final static Logger logger = LoggerFactory.getLogger(SqlFactory.class);
    
    private Map<String,Object> objectToMap(Object entity) {
        Field[] fields = entity.getClass().getDeclaredFields();
        Map<String,Object> map = new HashMap<String,Object>();
        for(Field field : fields) {
            field.setAccessible(true);//容許訪問屬性
            Object value = null;
            try {
                value = field.get(entity);
            } catch (IllegalArgumentException | IllegalAccessException e) {
                e.printStackTrace();
            }
            if(value != null) {
                map.put(field.getName(), value);
            }
        }
        return map;
    }
    
    public String getDeleteSql() {
        StringBuilder sql = new StringBuilder("delete from ").append(tableName).append(" where id = ?");
        logger.info(sql.toString());
        return sql.toString();
    }
    
    public String getSelectOneSql() {
        StringBuilder sql = new StringBuilder("select * from ").append(tableName).append(" where id = ?");
        logger.info(sql.toString());
        return sql.toString();
    }
    
    public String getInsertSql(Object entity) {
        Map<String,Object> map = this.objectToMap(entity);
        map.remove("id");
        params = new Object[map.size()];
        StringBuilder stringBuiler = new StringBuilder("insert into ").append(tableName).append("(");
        for(String key : map.keySet()) {
            stringBuiler.append(key).append(",");
        }
        stringBuiler.deleteCharAt(stringBuiler.length()-1).append(") values (");
        int i = 0;
        for(String key : map.keySet()) {
            stringBuiler.append("?,");
            params[i] = map.get(key);
            i++;
        }
        stringBuiler.deleteCharAt(stringBuiler.length()-1).append(")");
        map = null;
        logger.info(stringBuiler.toString());
        return stringBuiler.toString();
    }
    
    public String getUpdateSql(Object entity) {
        Map<String,Object> map = this.objectToMap(entity);
        params = new Object[map.size()];
        params[params.length-1] = map.remove("id");
        StringBuilder stringBuiler = new StringBuilder("update ").append(tableName).append(" set ");
        int i = 0;
        for(String key : map.keySet()) {
            stringBuiler.append(key).append("=?,");
            params[i] = map.get(key);
            i++;
        }
        stringBuiler.deleteCharAt(stringBuiler.length()-1).append(" where id = ?");
        map = null;
        logger.info(stringBuiler.toString());
        return stringBuiler.toString();
    }
    
    public String getSelectList(Object entity) {
        Map<String,Object> map = this.objectToMap(entity);
        map.remove("id");
        params = new Object[map.size()];
        StringBuilder stringBuiler = new StringBuilder("select * from ").append(tableName).append(" where ");
        int i = 0;
        for(String key : map.keySet()) {
            stringBuiler.append(key).append("=? and ");
            params[i] = map.get(key);
            i++;
        }
        stringBuiler.delete(stringBuiler.length()-4, stringBuiler.length());
        map = null;
        logger.info(stringBuiler.toString());
        return stringBuiler.toString();
    }
}
SqlFactory

 

 6.須要有一個通用的Dao接口及實現類來完成核心操做

package club.xcreeper.springboot_jdbctemplete.Core.dao;

import java.io.Serializable;
import java.util.List;

public interface CoreDao<T> {
    int insert(T t);
    int delete(Serializable id);
    int update(T t);
    T getOne(Serializable id);
    List<T> getList(T t);
}
CoreDao
package club.xcreeper.springboot_jdbctemplete.Core.dao.impl;

import club.xcreeper.springboot_jdbctemplete.Core.dao.CoreDao;
import club.xcreeper.springboot_jdbctemplete.util.SqlFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.util.List;

public class CoreDaoImpl<T> implements CoreDao<T> {

    private Class<T> clazz;

    private SqlFactory sqlFactory;

    @SuppressWarnings("unchecked")
    public CoreDaoImpl() {
        this.clazz =  (Class<T>)((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
        sqlFactory = new SqlFactory(this.clazz);
    }

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public int insert(T t) {
        return jdbcTemplate.update(sqlFactory.getInsertSql(t),sqlFactory.params);
    }

    @Override
    public int delete(Serializable id) {
        return jdbcTemplate.update(sqlFactory.getDeleteSql(),id);
    }

    @Override
    public int update(T t) {
        return jdbcTemplate.update(sqlFactory.getUpdateSql(t),sqlFactory.params);
    }

    @Override
    public T getOne(Serializable id) {
        return jdbcTemplate.queryForObject(sqlFactory.getSelectOneSql(),new BeanPropertyRowMapper<T>(this.clazz),id);

    }

    @Override
    public List<T> getList(T t) {
        return jdbcTemplate.query(sqlFactory.getSelectList(t),new BeanPropertyRowMapper<T>(this.clazz),sqlFactory.params);
    }
}
CoreDaoImpl

 

7. 實體類

package club.xcreeper.springboot_jdbctemplete.entity;

import lombok.Getter;
import lombok.Setter;
import lombok.ToString;

@ToString
public class User {
    @Setter
    @Getter
    private Integer id;
    @Setter
    @Getter
    private String username;
    @Setter
    @Getter
    private String password;
}
User
package club.xcreeper.springboot_jdbctemplete.entity;

import lombok.Getter;
import lombok.Setter;
import lombok.ToString;

@ToString
public class Phone {
    @Getter@Setter
    private Integer id;
    @Getter@Setter
    private String brand;
    @Getter@Setter
    private Integer user_id;
}
Phone

 

8. dao接口及其實現,只需繼承核心dao便可

package club.xcreeper.springboot_jdbctemplete.dao;

import club.xcreeper.springboot_jdbctemplete.Core.dao.CoreDao;
import club.xcreeper.springboot_jdbctemplete.entity.User;

public interface UserDao extends CoreDao<User> {

}
UserDao
package club.xcreeper.springboot_jdbctemplete.dao;

import club.xcreeper.springboot_jdbctemplete.Core.dao.CoreDao;
import club.xcreeper.springboot_jdbctemplete.entity.Phone;

public interface PhoneDao extends CoreDao<Phone> {

}
PhoneDao
package club.xcreeper.springboot_jdbctemplete.dao.impl;

import club.xcreeper.springboot_jdbctemplete.Core.dao.impl.CoreDaoImpl;
import club.xcreeper.springboot_jdbctemplete.dao.UserDao;
import club.xcreeper.springboot_jdbctemplete.entity.User;
import org.springframework.stereotype.Repository;

@Repository
public class UserDaoImpl extends CoreDaoImpl<User> implements UserDao {
}
UserDaoImpl
package club.xcreeper.springboot_jdbctemplete.dao.impl;

import club.xcreeper.springboot_jdbctemplete.Core.dao.impl.CoreDaoImpl;
import club.xcreeper.springboot_jdbctemplete.dao.PhoneDao;
import club.xcreeper.springboot_jdbctemplete.entity.Phone;
import org.springframework.stereotype.Repository;

@Repository
public class PhoneDaoImpl extends CoreDaoImpl<Phone> implements PhoneDao {
}
PhoneDaoImpl

 

9. service接口及其實現

package club.xcreeper.springboot_jdbctemplete.service;

import club.xcreeper.springboot_jdbctemplete.entity.User;

import java.util.List;

public interface UserService {
    int insert(User user);
    int delete(int id);
    int update(User user);
    User getOne(int id);
    List<User> getList(User user);
}
UserService
package club.xcreeper.springboot_jdbctemplete.service;

import club.xcreeper.springboot_jdbctemplete.entity.Phone;

import java.util.List;

public interface PhoneService {
    int insert(Phone phone);
    int delete(int id);
    int update(Phone phone);
    Phone getOne(int id);
    List<Phone> getList(Phone phone);
}
PhoneService
package club.xcreeper.springboot_jdbctemplete.service.impl;

import club.xcreeper.springboot_jdbctemplete.dao.UserDao;
import club.xcreeper.springboot_jdbctemplete.entity.User;
import club.xcreeper.springboot_jdbctemplete.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;

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

    @Override
    public int delete(int id) {
        return userDao.delete(id);
    }

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

    @Override
    public User getOne(int id) {
        return userDao.getOne(id);
    }

    @Override
    public List<User> getList(User user) {
        return userDao.getList(user);
    }
}
UserServiceImpl
package club.xcreeper.springboot_jdbctemplete.service.impl;

import club.xcreeper.springboot_jdbctemplete.dao.PhoneDao;
import club.xcreeper.springboot_jdbctemplete.entity.Phone;
import club.xcreeper.springboot_jdbctemplete.service.PhoneService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class PhoneServiceImpl implements PhoneService {

    @Autowired
    private PhoneDao phoneDao;

    @Override
    public int insert(Phone phone) {
        return phoneDao.insert(phone);
    }

    @Override
    public int delete(int id) {
        return phoneDao.delete(id);
    }

    @Override
    public int update(Phone phone) {
        return phoneDao.update(phone);
    }

    @Override
    public Phone getOne(int id) {
        return phoneDao.getOne(id);
    }

    @Override
    public List<Phone> getList(Phone phone) {
        return phoneDao.getList(phone);
    }
}
PhoneServiceImpl

 

10. controller

package club.xcreeper.springboot_jdbctemplete.controller;

import club.xcreeper.springboot_jdbctemplete.entity.User;
import club.xcreeper.springboot_jdbctemplete.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping(value = "/{id}")
    public User getOne(@PathVariable int id) {
        return userService.getOne(id);
    }

    @GetMapping(params = {"username","password","username!=","password!="})
    public List<User> getList(User user) {
        return userService.getList(user);
    }


}
UserController

 

11. 啓動項目,並用postman測試接口

相關文章
相關標籤/搜索