最近学到springboot与jdbc的整合部分,用作复习。
当开发项目较小,Mybatis相对于jdbc来说,还是显得稍微笨重一些,而且,由于Mybatis重重封装jdbc,在代码运行效率上也不如更接近底层的jdbc。
环境
jdk1.8 intelliJ IDEA
springboot jdbc 相关整合包
步骤:
一、建立springboot项目
利用IDEA开发工具建立springboot项目,引入如下依赖:(需要联网支持)
二、编写入口类及MySQL相关配置application.properties:
入口类代码:
package com;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
//springboot入口类
public class Application1 {
public static void main(String[] args) {
SpringApplication.run(Application1.class, args);
}
}
入口类注意工程结构位置,入口类与其他子包同级:
这里附张数据库的图:
三、编写DAO层及领域对象代码:
package com.dao;
import com.domain.Student;
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.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;
import java.util.List;
/*
* @author F3ver1
* @date 2019/2/24 16:59
*/
@Repository
public class StudentDao {
@Autowired
private JdbcTemplate jdbc;
public void insert(String sname, String sex, Date birthday) {
String sql = "insert into student(sname,sex,birthday)values(?,?,?)";
jdbc.update(sql, sname, sex, birthday);
}
//查询整张表返回一个学生集合
public List<Student> findAll() {
String sql = "select * from student";
return jdbc.query(sql, new RowMapper<Student>() {
//rowMapper的含义是指数据库的每行数据映射到一个java领域对象
@Override
public Student mapRow(ResultSet resultSet, int i) throws SQLException {
Student student = new Student();
student.setSid(resultSet.getInt("sid"));
student.setSname(resultSet.getString("sname"));
student.setBirthday(resultSet.getDate("birthday"));
student.setSex(resultSet.getString("sex"));
return student;
}
});
}
//简化方法findAll()
//springboot针对java对象的属性与数据库列名相同时,有简便的映射方法
public List<Student> findAll2() {
String sql = "select * from student";
return jdbc.query(sql, new BeanPropertyRowMapper<>(Student.class));
}
}
四、编写Controller控制层类:
package com.controller;
import com.dao.StudentDao;
import com.domain.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.Date;
import java.util.List;
@Controller
public class StudentController {
@Autowired
private StudentDao studentDao;
@RequestMapping("/insert")
@ResponseBody
public void insert(String sname,String sex, @DateTimeFormat(pattern = "yyyy-MM-dd") Date birthday) {
studentDao.insert(sname,sex,birthday);
}
@RequestMapping("/findAll")
@ResponseBody
public List<Student> findAll() {
return studentDao.findAll();
}
}
insert():
findAll():findAll2()方法需要数据库列名与领域对象属性名相同时,才可以使用。