注:由整合(续):
所有的配置文件在哪里找的都会 一 一详解
支持hibernate,并完成简单的查询操作
拷jar包
找到你的框架源文件--->\hibernate-release-5.2.2.Final\hibernate-release-5.2.2.Final\lib\required只需要copy----》required里的所有jar包即可删除重复jar包(留高版本删低版本)
添加hibernate的核心配置文件
在src的根目录下创建一个xml文件(一般名字为:hibernate.cfg.xml)---->是可以随意取名字的复制hibernate所需要的DTD--->找到框架源文件下的hibernate.cfg.xml---->(hibernate-release-5.2.2.Final\hibernate-release-5.2.2.Final\project\etc\hibernate.cfg.xml)拷贝头上的DTD----其他的一律不要配置核心文件<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/ssh</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">root</property>
<!-- 官方语言 -->
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- sql语句 -->
<property name="hibernate.show_sql">true</property>
<!-- 格式化 -->
<property name="hibernate.format_sql">true</property>
<!-- 自动更新表结构 -->
<property name="hibernate.hbm2ddl.auto">update</property>
<!-- 引入映射文件 -->
<mapping resource="/com/bjsxt/user/pojo/AUser.hbm.xml"/>
</session-factory>
</hibernate-configuration>解释:
hibernate-configguration为hibernate配置文件的根节点主要是配置session-factory:相当于jdbc里面的connection,就是一个链接数据的链接池property:属性是配置参数(链接数据的参数)----》所有的键值对都是从\hibernate-release-5.2.2.Final\hibernate-release-5.2.2.Final\project\etc里的hibernate.properties属性文件里找到的,可以配置所有的数据库mapping:是添加pojo的映射文件---后面再说 hibernate的配置文件完成
让spring支持hibernate框架
在spring配置文件中支持hibernate配置<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd"
default-autowire="byName">
<!-- 扫描那些包 -->
<context:component-scan base-package="com.bjsxt" />
<!-- 支持hibernate -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<!-- 引入hibernate的配置文件 -->
<property name="configLocations" value="classpath:hibernate.cfg.xml" />
</bean>
</beans>解释:要让spring支持hibernate只需要在spring配置文件中配置一个sessionFactory的类即可属性配置:property:中name=configLoaction是从这个localSessionFactory类里的属性,配置上hibernate的核心配置文件即可
实现简单的查询操作(涉及到一个ocp原则(开放封闭原则))
创建表结构id int 11 0 0 -1 0 0 0 0 角色id -1 0
name varchar 255 0 0 0 0 0 0 0 角色名称 utf8 utf8_general_ci 0
email varchar 255 0 0 0 0 0 0 0 email utf8 utf8_general_ci 0 0
status tinyint 4 0 0 0 0 0 0 0 角色状态 0 0
updateTime datetime 0 0 0 0 0 0 0 0 更新时间
reateTime datetime 0 0 0 0 0 0 0 0 创建时间
lastLoginTime datetime 0 0 0 0 0 0 0 0 上次登录时间
创建pojopublic class AUser
{
private int id;
private String name;
private String email;
private byte status;
private Date updateTime;
private Date createTime;
private Date lastLoginTime;}get/set 略
创建映射文件<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<!-- 匹配的类 -->
<class name="com.bjsxt.user.pojo.AUser" table="a_user">
<!-- 主键 -->
<id name="id">
<!-- 主键生成策略 -->
<generator class="native"/>
</id>
<!-- 其他属性 -->
<property name="email"/>
<property name="name"/>
<property name="status"/>
<property name="createTime"/>
<property name="updateTime"/>
<property name="lastLoginTime"/>
</class>
</hibernate-mapping>解释:在和pojo相同的路径下创建一个xml,文件名一般为:类名.hbm.xml,DTD从这里看吧 忘记了,hibernate-mapping为根节点,class,表示对应的类,table表示对应的表,id表示主键,generator,表示主键生成策略,其他属性,(要在hiberntae配置文件中将映射的配置文件引入) 创建所有的dao的父类,以及实现类---->实现ocp原则package com.bjsxt.commom.dao;
import java.util.Map;
public interface IBasicDao<T>
{
/**
* 保存一个对象
* @param t
* @return 返回的为主键,若等于0 为失败
*/
int insert(T t);
/**
* 查询一条记录
* @param condMap
* @return
*/
T findOne(String hql,Map<String,Object> condMap);
}
实现类:package com.bjsxt.commom.dao.impl;
import java.util.Map;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.query.Query;
import org.springframework.orm.hibernate5.HibernateCallback;
import org.springframework.orm.hibernate5.support.HibernateDaoSupport;
import com.bjsxt.commom.dao.IBasicDao;
public abstract class BasicDaoImpl<T> extends HibernateDaoSupport implements IBasicDao<T>
{
/*
* 保存一个对象
* */
@Override
public int insert(T t)
{
return (int) this.getHibernateTemplate().save(t);
}
/*
* 抽象方法要求继承的子类重写,为自己的findone写条件
* */
public abstract T findOne(String type,Map<String,Object> sourceMap);
/**
* 查询一条记录
*/
protected T findOneDao(String hql,Map<String, Object> condMap)
{
return this.getHibernateTemplate().execute(new HibernateCallback<T>()
{
@Override
public T doInHibernate(Session session) throws HibernateException
{
/*
* session = connection 一个链接
*
* 获得一个query对象 == preparedStatement
* */
try
{
Query<T> query = session.createQuery(hql);
/* 设置参数 */
query.setProperties(condMap);
return query.getSingleResult();
} catch (Exception e)
{
return null;
}
}
});
}
}
dao:package com.bjsxt.user.dao.impl;
import java.util.HashMap;
import java.util.Map;
import org.springframework.stereotype.Repository;
import com.bjsxt.commom.dao.impl.BasicDaoImpl;
import com.bjsxt.user.dao.IAUserDao;
import com.bjsxt.user.pojo.AUser;
@Repository("userDao")
public class AUserDaoImpl extends BasicDaoImpl<AUser> implements IAUserDao
{
/**
* 为父类的方法拼接条件
*/
@Override
public AUser findOne(String type, Map<String, Object> sourceMap)
{
Map<String,Object> condMap = new HashMap<String,Object>();
StringBuffer hqlsb = new StringBuffer();
hqlsb.append(" from AUser au where 1 = 1 ");
if(!"".equalsIgnoreCase(sourceMap.get("id")+"") && sourceMap.get("id")!= null)
{
hqlsb.append(" and id = :id ");
condMap.put("id", Integer.valueOf(sourceMap.get("id")+""));
}else if(!"".equalsIgnoreCase(sourceMap.get("password")+"") && sourceMap.get("password")!= null
&& "".equalsIgnoreCase(sourceMap.get("email")+"") && sourceMap.get("email")!= null)
{
hqlsb.append(" and email = :email and password = :password ");
condMap.put("email", sourceMap.get("email"));
condMap.put("password", sourceMap.get("password"));
}else
{
return null;
}
hqlsb.append(" order by au.createTime desc");
return this.findOneDao(hqlsb.toString(), condMap);
}
}
service:package com.bjsxt.user.service.impl;
import java.util.Map;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import com.alibaba.fastjson.JSONObject;
import com.bjsxt.user.dao.IAUserDao;
import com.bjsxt.user.pojo.AUser;
import com.bjsxt.user.service.IUserService;
@Service("userService")
public class UserServiceImpl implements IUserService
{
@Resource
private IAUserDao userDao;
@Override
public AUser findUserService(String type, Map<String, Object> sourceMap)
{
return this.userDao.findOne(type, sourceMap);
}
/**
* @return code:1 表示成功 0 表示失败
*
*/
@Override
public JSONObject insertUserService(AUser user)
{
JSONObject jsonObject = new JSONObject();
int insert = this.userDao.insert(user);
if(insert>0)
{
jsonObject.put("code", "1");
jsonObject.put("info", "用户添加成功");
}else
{
jsonObject.put("code", "0");
jsonObject.put("info", "用户添加成功");
}
return jsonObject;
}
}
所有接口略:
junit测试
父类:package com.bjsxt.commom.test;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.bjsxt.commom.Util.constantFinalUtil;
public class BasicTest
{
protected ApplicationContext applicationContext;
@Before
public void infoSpring()
{
applicationContext = new ClassPathXmlApplicationContext("classpath:spring/applicationContext_*.xml");
}
@Test
public void testSucceed()
{
constantFinalUtil.LOGGER.info("----applicationContext==={}------------",applicationContext);
}
} 测试类:package com.bjsxt.user;
import java.util.HashMap;
import java.util.Map;
import org.junit.Before;
import org.junit.Test;
import com.bjsxt.commom.Util.constantFinalUtil;
import com.bjsxt.commom.test.BasicTest;
import com.bjsxt.user.pojo.AUser;
import com.bjsxt.user.service.IUserService;
public class TestUserService extends BasicTest
{
private IUserService userService;
@Before
public void info()
{
userService = (IUserService) this.applicationContext.getBean("userService");
}
@Test
public void test()
{
constantFinalUtil.LOGGER.info("--test--{}",userService);
}
@Test
public void findUserService()
{
Map<String, Object> sourceMap = new HashMap<String,Object>();;
sourceMap.put("id", 1);
AUser user = this.userService.findUserService("", sourceMap );
constantFinalUtil.LOGGER.info("--user--{}",user);
}
}
结果:- --user--AUser [id=1, name=1, email=1, status=1, updateTime=2016-12-13 11:04:12.0, createTime=2016-12-21 11:04:14.0, lastLoginTime=2016-12-06 11:04:16.0]
只写了一个最简单的查询单条的记录,如果是其他操作需要用到事物管理器,后续补
转载请注明原文地址: https://ju.6miu.com/read-968797.html