第一步先写DBAccess类
package com.lj.util;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
/**
* 提供了一组获得或关闭数据库对象的方法
*
*/
public class DBAccess {
private static String driver;
private static String url;
private static String user;
private static String password;
static {// 静态块执行一次,加载 驱动一次
try {
InputStream is = DBAccess.class
.getResourceAsStream("config.properties");
Properties properties = new Properties();
properties.load(is);
driver = properties.getProperty("driver");
url = properties.getProperty("url");
user = properties.getProperty("user");
password = properties.getProperty("pwd");
Class.forName(driver);
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
/**
* 获得数据连接对象
*
* @return
*/
public static Connection getConnection() {
try {
Connection conn = DriverManager.getConnection(url, user, password);
return conn;
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
public static void close(ResultSet rs) {
if (null != rs) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
}
public static void close(Statement stmt) {
if (null != stmt) {
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
}
public static void close(Connection conn) {
if (null != conn) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
}
public static void close(Connection conn, Statement stmt, ResultSet rs) {
close(rs);
close(stmt);
close(conn);
}
public static boolean isOracle() {
return "oracle.jdbc.driver.OracleDriver".equals(driver);
}
public static boolean isSQLServer() {
return "com.microsoft.sqlserver.jdbc.SQLServerDriver".equals(driver);
}
public static boolean isMysql() {
return "com.mysql.jdbc.Driver".equals(driver);
}
public static void main(String[] args) {
Connection conn = DBAccess.getConnection();
DBAccess.close(conn);
System.out.println("isOracle:" + isOracle());
System.out.println("isSQLServer:" + isSQLServer());
System.out.println("isMysql:" + isMysql());
System.out.println("数据库连接(关闭)成功");
}
}
config.properties
代码:
#mysql5
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis_ssm?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT
user=root
pwd=123
然后在运行结果
book实体类
package com.lj.entity;
public class Book {
private int bid;
private String bname;
private float price;
public Book() {
// TODO Auto-generated constructor stub
}
public Book(int bid, String bname, float price) {
super();
this.bid = bid;
this.bname = bname;
this.price = price;
}
@Override
public String toString() {
return "Book [bid=" + bid + ", bname=" + bname + ", price=" + price + "]";
}
public int getBid() {
return bid;
}
public void setBid(int bid) {
this.bid = bid;
}
public String getBname() {
return bname;
}
public void setBname(String bname) {
this.bname = bname;
}
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
}
bookDao 方法类
public List<Book> list(Book book,PageBean pageBean) throws SQLException, InstantiationException, IllegalAccessException{
String sql = "select * from t_mvc_book where true";
if(StringUtils.isNotBlank(book.getBname())) {
sql += " and bname like '%"+book.getBname()+"%'";
}
return super.executeQuery(sql, Book.class, pageBean);
}
public static void main(String[] args){
BookDao bookDao=new BookDao();
Book book=new Book();
// book.setBname("龙王传说");
PageBean pageBean=new PageBean();
pageBean.setPage(2);
pageBean.setPagination(false);
try {
List<Book> list=bookDao.list(book, null);//填入null就是输出所有内容
for (Book b : list) {
System.out.println(b);
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
}
PageBean
public class PageBean {
private int page = 1;// 页码
private int rows = 10;// 页大小
private int total = 0;// 总记录数
private boolean pagination = true;// 是否分页
public PageBean() {
super();
}
public int getPage() {
return page;
}
public void setPage(int page) {
this.page = page;
}
public int getRows() {
return rows;
}
public void setRows(int rows) {
this.rows = rows;
}
public int getTotal() {
return total;
}
public void setTotal(int total) {
this.total = total;
}
public void setTotal(String total) {
this.total = Integer.parseInt(total);
}
public boolean isPagination() {
return pagination;
}
public void setPagination(boolean pagination) {
this.pagination = pagination;
}
/**
* 获得起始记录的下标
*
* @return
*/
public int getStartIndex() {
return (this.page - 1) * this.rows;
}
@Override
public String toString() {
return "PageBean [page=" + page + ", rows=" + rows + ", total=" + total + ", pagination=" + pagination + "]";
}
}
BaseDao
/**
*
* @param sql 不同的sql语句所以需要传递;
* @param clz 生产出不同的实体类对应的实列,然后装进list容器中
* @param pageBean 决定是否分页
* @return
* @throws SQLException
* @throws InstantiationException
* @throws IllegalAccessException
*/
public List<T> executeQuery(String sql,Class clz,PageBean pageBean) throws SQLException, InstantiationException, IllegalAccessException{
Connection con= DBAccess.getConnection();
PreparedStatement ps = null;
ResultSet rs=null;
if(pageBean!=null && pageBean.isPagination()) {
// 3、考虑该方法可以进行分页
// 需要分页
// 3.1 算符合总记录数
String consql=getconsql(sql);
ps = con.prepareStatement(consql);
rs=ps.executeQuery();
if(rs.next()) {
//算总记录数
pageBean.setTotal(rs.getLong(1)+"");
}
// 3.2 查询出符合条件的结果集
String setsql=getsetsql(sql,pageBean);
ps = con.prepareStatement(setsql);
rs=ps.executeQuery();
}else {
ps = con.prepareStatement(sql);
rs=ps.executeQuery();
}
List<T> list=new ArrayList<>();
T t;
while(rs.next()) {
//list.add(new Book(rs.getInt("bid"),rs.getString("bname") , rs.getFloat("price")));
//1:实列化一个对象(该对象是空的,里面的属性没有值)
//2:去book的所有属性,然后给其赋值
//2.1 获取所有属性对象
//2.2 给属性对象赋值
//3:然后装进list
//给属性赋值
t= (T)clz.newInstance();
Field[] fileds = clz.getDeclaredFields();
for (Field field : fileds) {
field.setAccessible(true);
//注意:这样去给属性赋值,就要保证实体类的属性名要跟数据库的列名一致
field.set(t, rs.getObject(field.getName()));
}
list.add(t);
}
DBAccess.close(con, ps, rs);
return list;
}
private String getsetsql(String sql, PageBean pageBean) {
//利用原生sql拼接出符合条件的结果集的查询sql
return sql+" limit "+ pageBean.getStartIndex()+","+pageBean.getRows();
}
private String getconsql(String sql) {
//获取符合条件的总记录数的sql语句
return "select count(*) from ("+sql+")t";
}
}
下面是处理乱码
public class EncodingFiter implements Filter {
private String encoding = "UTF-8";// 默认字符集
public EncodingFiter() {
super();
}
public void destroy() {
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse res = (HttpServletResponse) response;
// 中文处理必须放到 chain.doFilter(request, response)方法前面
res.setContentType("text/html;charset=" + this.encoding);
if (req.getMethod().equalsIgnoreCase("post")) {
req.setCharacterEncoding(this.encoding);
} else {
Map map = req.getParameterMap();// 保存所有参数名=参数值(数组)的Map集合
Set set = map.keySet();// 取出所有参数名
Iterator it = set.iterator();
while (it.hasNext()) {
String name = (String) it.next();
String[] values = (String[]) map.get(name);// 取出参数值[注:参数值为一个数组]
for (int i = 0; i < values.length; i++) {
values[i] = new String(values[i].getBytes("ISO-8859-1"),
this.encoding);
}
}
}
chain.doFilter(request, response);
}
public void init(FilterConfig filterConfig) throws ServletException {
String s = filterConfig.getInitParameter("encoding");// 读取web.xml文件中配置的字符集
if (null != s && !s.trim().equals("")) {
this.encoding = s.trim();
}
}
}
StringUtils类
public class StringUtils {
// 私有的构造方法,保护此类不能在外部实例化
private StringUtils() {
}
/**
* 如果字符串等于null或去空格后等于"",则返回true,否则返回false
*
* @param s
* @return
*/
public static boolean isBlank(String s) {
boolean b = false;
if (null == s || s.trim().equals("")) {
b = true;
}
return b;
}
/**
* 如果字符串不等于null或去空格后不等于"",则返回true,否则返回false
*
* @param s
* @return
*/
public static boolean isNotBlank(String s) {
return !isBlank(s);
}
}