intellij idea 构建 基于spring springmvc hibernate的maven项目《二》

时间:2022-02-27 09:54:50

这一节主要讲的是具体数据库,dao,service,controller层操作

1.设置java文件目录

打开project structure (工具栏打开,或者file->projectstructure),在modules下,找到工程,右键main目录,newfolder,创建新的文件夹。

intellij idea 构建 基于spring springmvc hibernate的maven项目《二》

这里取名叫java,然后选中java文件夹,mark as  sources   在右侧可以看到已经标志为sources了。 intellij idea 构建 基于spring springmvc hibernate的maven项目《二》


完成后可以看到,工程下main已经多了一个名为java的文件夹,在java文件夹中创建包名,采用mvc 的方式命名 com.xxx.test.model  com.xxx.test.dao  com.xxx.test.daoImpl  com.xxx.test.service  com.xxx.test.controller   intellij idea 构建 基于spring springmvc hibernate的maven项目《二》

下面开始连接数据库 在右侧点开database intellij idea 构建 基于spring springmvc hibernate的maven项目《二》
新建mysql连接,并填入相应的信息,apply intellij idea 构建 基于spring springmvc hibernate的maven项目《二》
连接成功后会在屏幕右侧看到数据库的具体信息 intellij idea 构建 基于spring springmvc hibernate的maven项目《二》
此时说明数据库已经连接成功,接下来根据数据库表格信息生成model信息 在页面左侧会出现persistence页面intellij idea 构建 基于spring springmvc hibernate的maven项目《二》如果左侧没有persistence窗口,可以通过菜单栏View -》tool windows 打开persistence。打开后可以看到已经连接的数据库信息,选择数据库右键 Generate Persistence Mapping > By Database Schema. intellij idea 构建 基于spring springmvc hibernate的maven项目《二》
如上图所示,选择数据库表,生成映射model类(指定包名),红色标注部分,可以根据自己的需要选择生成单个的.hbm映射文件还是通过注解的方式映射(效果都一样),我这儿选择的通过注解的方式映射。 完成后页面如下,model自动生成了intellij idea 构建 基于spring springmvc hibernate的maven项目《二》 接下来就是为model写相应的dao层接口及实现: 1)将所有model的dao层进行统一封装,得到基类 2)每个model的dao继承基类 具体代码如下(忘了何人做的封装类了): 接口IBaseDao
package com.htdz.dao;
import java.sql.SQLException;
import java.util.Collection;
import java.util.List;
import com.htdz.model.Page;
import com.htdz.util.Parameter;
import org.hibernate.HibernateException;
public interface IBaseDao<T> {

//单个CRUD
public void save(final T entity) throws Exception;
public void delete(final T entity) throws Exception;
public void deleteWithHql(final String hql) throws Exception;
public void update(final T entity) throws Exception;
public T getOne(final int id) throws Exception;

//批处理
public int batchSave(final List<T> list) throws Exception;
public void deleteAll(final Collection entities) throws Exception;//删不掉?

//createQuery(Query)
public T findOne(final String hql) throws Exception;
public T findOne(final String hql, final Parameter parameter) throws Exception;

//list查询
public List<T> findList(final String hql) throws Exception;
public List<T> findList(final String hql, final Parameter parameter) throws Exception;

//分页查询
public Page<T> findPage(final int currentPage, final int pageSize, final String queryHql, final String countHql, final Object[] values)
throws HibernateException,SQLException;
public Page<T> findPage(final int currentPage, final int pageSize, final String queryHql, final String countHql)
throws HibernateException,SQLException;

//查询满足条件的记录数
public long findCount(final String hql);
public long findCount(final String hql, final Object[] values);
}
实现类BaseDaoImpl
package com.htdz.daoImpl;

import java.sql.SQLException;
import java.util.Collection;
import java.util.List;
import java.util.Set;

import javax.annotation.Resource;

import com.htdz.dao.IBaseDao;
import com.htdz.model.Page;
import com.htdz.util.Parameter;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

public class BaseDaoImpl<T> implements IBaseDao<T> {

private int BATCH_MAX_ROW = 5;

private SessionFactory sessionFactory;
//使用spring配合hibernateTemplate来管理Transaction(结果不理想)
//@Autowired //干脆不用hibernateTemplate来操作了,事务处理时遇到太多问题
//private HibernateTemplate hibernateTemplate;
private Class<T> entityClass;

//construct methods
public BaseDaoImpl(){
}

public BaseDaoImpl(Class<T> entityClass){
this.entityClass = entityClass;
}


@Override
public void save(T entity) throws Exception {
Session session = this.getSession();
session.beginTransaction();
session.save(entity);
session.getTransaction().commit();
}

@Override
public int batchSave(List<T> list) throws Exception {
Session session = this.getSession();
session.beginTransaction();
for (int i = 0; i < list.size(); ++i) {
session.save(list.get(i));
if (i % BATCH_MAX_ROW == 0) {
session.flush();
session.clear();
}
}
session.flush();
session.clear();
session.getTransaction().commit();
return list.size();
}

@Override
public void deleteAll(Collection entities) throws Exception {
Session session = this.getSession();
session.beginTransaction();
for (Object entity : entities) {
session.delete(entity);
}
session.getTransaction().commit();
}

@Override
public void delete(T entity) throws Exception {
Session session = this.getSession();
session.beginTransaction();
session.delete(entity);
session.getTransaction().commit();
}

@Override
public void deleteWithHql(String hql) throws Exception {
Session session = this.getSession();
session.beginTransaction();
Query query = session.createQuery(hql);
query.executeUpdate();
session.getTransaction().commit();
}

@Override
public void update(T entity) throws Exception {
Session session = this.getSession();
session.beginTransaction();
session.update(entity);
session.getTransaction().commit();
}

@SuppressWarnings("unchecked")
@Override
public T getOne(int id) throws Exception {
Session session = this.getSession();
session.beginTransaction();
Object returnObject = session.get(entityClass, id);
session.getTransaction().commit();

return (T) returnObject;
}

@Override
public T findOne(String hql) throws Exception {
return findOne(hql,null);
}

@SuppressWarnings("unchecked")
@Override
public T findOne(final String hql, final Parameter parameter) throws Exception {
Session session = this.getSession();
session.beginTransaction();
Query query = session.createQuery(hql);
setParameter(query, parameter);
Object returnObject = query.setMaxResults(1).uniqueResult();
session.getTransaction().commit();

return (T) returnObject;
}

@Override
public List<T> findList(final String hql) throws Exception {
return findList(hql, null);
}

@SuppressWarnings("unchecked")
@Override
public List<T> findList(final String hql, final Parameter parameter) throws Exception {
Session session = this.getSession();
session.beginTransaction();
Query query = session.createQuery(hql);
setParameter(query, parameter);
List<T> returnList = query.list();
session.getTransaction().commit();

return returnList;
}

/**
*
* @param query
* @param parameter
* set sql parameters
*/
private void setParameter(Query query, Parameter parameter) {
if (parameter != null) {
Set<String> keySet = parameter.keySet();
for (String string : keySet) {
Object value = parameter.get(string);
if (value instanceof Collection<?>) {
query.setParameterList(string, (Collection<?>) value);
} else if (value instanceof Object[]) {
query.setParameterList(string, (Object[]) value);
} else {
query.setParameter(string, value);
}
}
}
}

public SessionFactory getSessionFactory() {
return sessionFactory;
}

@Resource(name="sessionFactory")//在applicationContext.xml文件中有配置
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}

/**
* @return session
*/
private Session getSession() {
return sessionFactory.getCurrentSession();
/* Configuration config = new Configuration().configure("applicationContext.xml");
sessionFactory = config.buildSessionFactory();
return sessionFactory.openSession();*/
}

@SuppressWarnings("unchecked")
@Override
public Page<T> findPage(int currentPage, int pageSize, String queryHql, String countHql, Object[] values)
throws HibernateException, SQLException {
Session session = this.getSession();
session.beginTransaction();
Query query = session.createQuery(queryHql);
if (values != null) {
for (int i = 0; i < values.length; i++) {
query.setParameter(i, values[i]);
}
}
// 如果pageSize<=0则查询全部,用于打印导出等...
if (pageSize > 0) {
query.setFirstResult(pageSize * (currentPage - 1));//设置要查询的结果集的开始索引位置
query.setMaxResults(pageSize);//设置要查询的结果集的数量
}
List<T> returnList = query.list();
session.getTransaction().commit();
long totalRecords = findCount(countHql, values);

return new Page<T>(returnList, totalRecords, currentPage, pageSize);
}

@Override
public Page<T> findPage(int currentPage, int pageSize, String queryHql, String countHql)
throws HibernateException, SQLException {
return findPage(currentPage, pageSize, queryHql, countHql, null);
}

@Override
public long findCount(String hql) {
return findCount(hql, null);
}

@Override
public long findCount(String hql, Object[] values) {
Session session = this.getSession();
session.beginTransaction();
Query query = session.createQuery(hql);
if (values != null) {
for (int i = 0; i < values.length; i++) {
query.setParameter(i, values[i]);
}
}
Long returnLong = (Long) query.setMaxResults(1).uniqueResult();
session.getTransaction().commit();

return returnLong;
}

}
辅助类Page
package com.xxxx.test.dao;import java.util.List;public class Page<T> {    private int current = 1;    private int total = 0;    private long records = 0;    private int size = 10;    private String orderBy = "";    private String order = "";    public String getOrderBy() {        return orderBy;    }    public void setOrderBy(String orderBy) {        this.orderBy = orderBy;    }    public String getOrder() {        return order;    }    public void setOrder(String order) {        this.order = order;    }    private List<T> list = null;    public Page() {    }    public Page(int currentPage, int pageSize){       current=currentPage;       size=pageSize;   }    public Page(List<T> list, int current, int size) {        this.current = current;        this.size = size;        this.list = list;    }        public Page(List<T> list, long records, int current, int size, String orderBy, String order) {        this.list = list;        this.current = current;        this.records = records;        this.size = size;        this.orderBy = orderBy;        this.order = order;        this.total = records == 0 ? 1 : (int) ((records - 1) / size + 1);//分几页的计算方法 if (this.current > this.total) {            this.current = this.total;        }        if (current < 1) {            this.current = 1;        }    }    public Page(List<T> list, long records, int current, int size) {        this(list, records, current, size, null, null);    }    public int getCurrent() {        return current;    }    public void setCurrent(int current) {        this.current = current;    }    public int getSize() {        return size;    }    public void setSize(int size) {        this.size = size;    }    public int getTotal() {        return total;    }    public void setTotal(int l) {        this.total = l;    }    public long getRecords() {        return records;    }    public void setRecords(long records) {        this.records = records;    }    public List<T> getList() {        return list;    }    public void setList(List<T> list) {        this.list = list;    }    @Override    public String toString() {        return "Page{" +                "current=" + current +                ", size=" + size +                ", list=" + list +                '}';    }}
辅助类 Parameter
package com.xxxx.test.dao;import java.util.HashMap;/** * 查询参数类 * */public class Parameter extends HashMap<String, Object> {    private static final long serialVersionUID = 1L;    /** * 构造类,例:new Parameter(id, parentIds) * * @param values 参数值 */ public Parameter(Object... values) {        if (values != null) {            for (int i = 0; i < values.length; i++) {                put("p" + i, values[i]);            }        }    }    /** * 构造类,例:new Parameter(new Object[][]{{"id", id}, {"parentIds", parentIds}}) * * @param parameters 参数二维数组 */ public Parameter(Object[][] parameters) {        if (parameters != null) {            for (Object[] os : parameters) {                if (os.length == 2) {                    put((String) os[0], os[1]);                }            }        }    }}

UserDao
package com.xxxx.test.dao;
import com.xxxx.test.model.UserEntity;/** * Created by yab on 2017/7/6. */public interface UserDao extends IBaseDao<BBasic> {}
UserDaoImpl
package com.xxxx.test.dao;

import com.xxxx.test.dao.UserDao;
import com.xxxx.test.model.UserEntity;

import org.springframework.stereotype.Component;

/**
* Created by yab on 2017/7/6.
*/
@Component
public class UserDaoImpl extends BaseDaoImpl<UserEntity> implements UserDao {

public UserDaoImpl(){
super(UserEntity.class);
}

}
基本工作完成了,下面就是写service层和controller层函数了