Spring Boot学习之旅:(十五)使用JdbcTemplate

来源:互联网 发布:pci串行端口驱动下载 编辑:程序博客网 时间:2024/06/11 21:50

在原有的基础上添加 mysql 连接和jpa 依赖

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

创建一个model

package com.wen.boot.model;import java.util.Date;import javax.persistence.Entity;import javax.persistence.GeneratedValue;import javax.persistence.GenerationType;import javax.persistence.Id;import com.alibaba.fastjson.annotation.JSONField;@Entitypublic class User {    private int id;    private String name;    private int age;    @JSONField(format="yyyy-mm-dd HH:mm")    private Date createTime;    private String remakes;    /** serialize  是否需要序列化     * @return the remakes     */    @JSONField(serialize=false)    public String getRemakes() {        return remakes;    }    public void setRemakes(String remakes) {        this.remakes = remakes;    }    public Date getCreateTime() {        return createTime;    }    public void setCreateTime(Date createTime) {        this.createTime = createTime;    }    @Id    @GeneratedValue(strategy=GenerationType.AUTO)    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 int getAge() {        return age;    }    public void setAge(int age) {        this.age = age;    }}

dao

public interface IUserDao {    public User getUserById(int id);}

dao 实现

@Repository("userDao")public class UserDaoImpl implements IUserDao {    @Resource    private JdbcTemplate jdbcTemplate;    public User getUserById(int id) {        String sql="select * from user where id=?";        RowMapper<User> user=new BeanPropertyRowMapper<User>(User.class);        return jdbcTemplate.queryForObject(sql,user,id);    }}

service

public interface IUserService {    public User getUserById(int id);}

service 实现

@Servicepublic class UserServiceImpl implements  IUserService{    @Resource(name="userDao")    private IUserDao userDao;       public User getUserById(int id) {        return userDao.getUserById(id);    }}

controller

@RestController@RequestMapping("/user")public class HelloContreller {    private Logger logger = LoggerFactory.getLogger(this.getClass());    @Autowired    public IUserService userService;    @GetMapping("/{id}")    public User getUser(@PathVariable int id) {        return userService.getUserById(id);    }}

启动工程 浏览器输入
http://localhost:8080/user/1
查看查询结果
这里写图片描述
本片文章只做整合JdbcTemplate 只做了简单的查询 如果还要实现其他的方法可以参考
http://www.cnblogs.com/heyongjun1997/p/5964256.html 这篇博客
文章地址:http://www.haha174.top/article/details/257327
项目源码: https://github.com/haha174/boot.git

原创粉丝点击