springmvc通常是先写实体,在数据库查询,最后增删改差,最感觉代码很冗余,自己在封装了一下。
常见的结构是:
entity:如
package com.liuxinquan.entiry;/** * @author:lxq * @类说明:Book * */public class Book { private String id; private String user_id; private String item_id; private String prefer; private String time; public String getId() { return id; } public String getUser_id() { return user_id; } public void setUser_id(String user_id) { this.user_id = user_id; } public String getItem_id() { return item_id; } public void setItem_id(String item_id) { this.item_id = item_id; } public String getPrefer() { return prefer; } public void setPrefer(String prefer) { this.prefer = prefer; } public String getTime() { return time; } public void setTime(String time) { this.time = time; } public void setId(String id) { this.id = id; }}
object:如
package com.liuxinquan.object;import java.sql.ResultSet;import java.sql.SQLException;import org.springframework.jdbc.core.RowMapper;import com.liuxinquan.entiry.Book;/** * @author:lxq * @类说明:bookobject * */public class BookObj implements RowMapper{ @Override public Book mapRow(ResultSet rs, int arg1) throws SQLException { Book book = new Book(); book.setId(rs.getString("id")); book.setItem_id(rs.getString("item_id")); book.setPrefer(rs.getString("prefer")); book.setTime(rs.getString("time")); book.setUser_id(rs.getString("user_id")); return book; } }
service
package com.liuxinquan.service;import java.util.List;import javax.annotation.Resource;import org.springframework.jdbc.core.JdbcTemplate;import org.springframework.stereotype.Service;import com.liuxinquan.entiry.Book;import com.liuxinquan.utils.CommonObj;/** * @author: @类说明: * */@Servicepublic class BookService { @Resource(name = "jdbcTemplate") public JdbcTemplate jdbcTemplate; public ListfindAll() { String sql = "select * from recommender_prefer "; List books = jdbcTemplate.query(sql, new bookObj()); return books; } public Book findbyId(String id) { String sql = "select * from recommender_prefer where id =" + id; Book book = jdbcTemplate.queryForObject(sql, new BookObj()); return book; } }
下面是简化的工具类
要是有很多实体,每写一个,都要重复这3个,效率很低,其中后两个是可以封装工具类:通用object
package com.liuxinquan.utils;import java.lang.reflect.Field;import java.sql.ResultSet;import java.sql.SQLException;import org.springframework.jdbc.core.RowMapper;/** * @author:lxq * @类说明:通用dao工具 * */public class CommonObj implements RowMapper这个可以放在utils中,具体用法如下:
package com.liuxinquan.service;import java.util.List;import javax.annotation.Resource;import org.springframework.jdbc.core.JdbcTemplate;import org.springframework.stereotype.Service;import com.liuxinquan.entiry.Book;import com.liuxinquan.utils.CommonObj;/** * @author: @类说明: * */@Servicepublic class BookService { @Resource(name = "jdbcTemplate") public JdbcTemplate jdbcTemplate; public List
service亦可以简化的,网上有很多,关于通用增删改查,自己可以搜一下。希望能有所帮助。