package com.test.dao;
import com.test.entity.ServiceTable;
import com.test.entity.UserTable;
import java.util.List;
/**
* @author Ming
* @date 2017/11/16 12:46
*/
public interface TestDao{
/**
* 通过一个 Integer 和一个 String 类型进行查询,返回一个对象
* @param id
* @param username
* @return
*/
UserTable getConditions(Integer id, String username);
/**
* 分页查询
* @param pageNumber
* @param pageSize
* @return
*/
List<UserTable> getPage(Integer pageNumber, Integer pageSize);
/**
* 查询所有 ,返回一个List集合
* @return
*/
List<UserTable> getAll2();
/**
* 返回一个 Integer 类型数据
* @return
*/
Integer getCount();
/**
* 根据id删除,不返回结果类型
* @param id
*/
void delete2(Integer id);
/**
* 查询 ServiceTable 主外键查询 ,返回一个List集合
* @param id
* @return
*/
List<ServiceTable> getAllService(Integer id);
}
package com.test.dao.impl;
import com.test.dao.TestDao;
import com.test.entity.ServiceTable;
import com.test.entity.UserTable;
import org.hibernate.*;
import org.springframework.stereotype.Repository;
import javax.annotation.Resource;
import java.util.List;
/**
* Hibernate Query Language(HQL): 是面向对象的查询语言
* Native SQL Queries(原生SQL) : 直接使用标准SQL语句
* Query By Criteria (QBC):Criteria叫标准化条件查询,是比HQL更面向对象的查询语句
*/
@Repository
public class TestDaoImpl implements TestDao {
@Resource
private SessionFactory sessionFactory;
public Session getSession() {
return sessionFactory.getCurrentSession();
}
/**
* 1:采用HQL语句:
* HQL语句中关键字不区分大小写,但是实体类和对象属性要区分大小写
* <p>
* :2:展现两种设置参数方法 =: , =?
* <p>
* :3:uniqueResult():
* 通过uniqueResult()方法,该方法返回一个Object对象,如果对象不存在则返回null,如果返回值不唯一,则抛出异常
*
* @param id
* @param username
* @return
*/
@Override
public UserTable getConditions(Integer id, String username) {
String hql = "from UserTable where id=:id AND username=:username";
Query query = getSession().createQuery(hql);
query.setParameter("id", id);
query.setParameter("username", username);
// String hql = "from UserTable where id=? AND username=?";
// Query query = getSession().createQuery(hql);
// query.setParameter(0 ,id);
// query.setString(1, username);
return (UserTable) query.uniqueResult();
}
/**
* :1:采用 原生SQL 语句:
* <p>
* :2:在使用原生SQL 语句的情况下--------》》》.addEntity(javabean.class) 返回一个集合对象,如果没有的话,不会报错,但是返回的将是一个数组
*
* @return
*/
@Override
public List<UserTable> getAll2() {
String sql = "select id, username, password, phone, creationTime from user_table";
SQLQuery sqlQuery = getSession().createSQLQuery(sql);
sqlQuery.addEntity(UserTable.class);
return sqlQuery.list();
}
/**
* 1:采用QBC
* 方法 描述
Restrictions.eq 对应sql中的 field = value
Restrictions.gt 对应sql中的 field > value
Restrictions.ge 对应sql中的 field >= value
Restrictions.lt 对应sql中的 field < value
Restrictions.le 对应sql中的 field <= value
Restrictions.between 对应sql中的 between
Restrictions.like 对应 like
Restrictions.in 对应 in
*
* @param pageNumber
* @param pageSize
* @return
*/
@Override
public List<UserTable> getPage(Integer pageNumber, Integer pageSize) {
Criteria criteria = getSession().createCriteria(UserTable.class);
criteria.setFirstResult(pageNumber);//设置查询的起始位置
criteria.setMaxResults(pageSize);//查询的条数
// criteria.add(Restrictions.like("username" ,"张"));
// criteria.add(Restrictions.eq("username" ,"张三"));
List list = criteria.list();
return list;
}
/**
* 1:采用HQL语句:不能使用 select * from ,但是可以使用别名 select stu from table_name
* 2:返回总条数 进行类型转换
*
* @return
*/
@Override
public Integer getCount() {
String hql = "select count(1) from UserTable";
String count = getSession().createQuery(hql).uniqueResult().toString();
return Integer.parseInt(count);
}
/**
* 1:.fiush() 清理缓存,执行SQL。
* 2:delete2只是一个示列,当然都是采用baseDao里面的delete
* 3:这里是原生SQL
*
* @param id
*/
@Override
public void delete2(Integer id) {
getSession().createSQLQuery("delete from user_table where id=" + id);
getSession().flush();
}
/**
* HQL语句 :
* fetch:抓取,查询关联属性,就不会出现延迟加载,用在连接查询中 跟在 join 后面,join fetch (适用于HQL中,如果使用在原生SQL中是会报错的)
* 能够有效的避免懒加载异常(LazyInitializationException)情况的发生
* @param id
* @return
*/
@Override
public List<ServiceTable> getAllService(Integer id) {
String hql = "from ServiceTable st inner join fetch st.userTableByUserid ut where ut.id=:id";
Query query = getSession().createQuery(hql);
query.setParameter("id" ,id);
return query.list();
}
}
package com.test.dao.impl;
import com.test.dao.TestDao;
import com.test.entity.ServiceTable;
import com.test.entity.UserTable;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.stereotype.Component;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.List;
/**
* @author Ming
* @date 2017/11/16 12:46
*/
@Component
@Transactional
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath*:applicationContext.xml")
public class TestDaoImplTest {
@Resource
private TestDao testDao;
@Test
public void getConditions() {
UserTable userTable = testDao.getConditions(1, "张三");
System.out.println(userTable.toString());
}
@Test
public void getPage() {
List<UserTable> userTableList = testDao.getPage(1, 5);
System.out.println(userTableList.size());
for (UserTable userTable : userTableList){
System.out.println(userTable.toString());
}
}
@Test
public void getAll2() {
List<UserTable> userTableList = testDao.getAll2();
for (UserTable userTable : userTableList){
System.out.println(userTable.toString());
}
}
@Test
public void getCount() {
Integer count = testDao.getCount();
System.out.println(count);
}
@Test
@Rollback(false)
public void delete2() {
testDao.delete2(7);
}
@Test
public void getAllService() {
List<ServiceTable> allService = testDao.getAllService(1);
for (ServiceTable serviceTable : allService){
System.out.println(serviceTable.toString());
}
}
}
CREATE TABLE `service_table` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键',
`imgurl` varchar(10000) DEFAULT NULL COMMENT '图片路径',
`title` varchar(50) DEFAULT NULL COMMENT '标题',
`userid` int(11) DEFAULT NULL COMMENT '发表人',
PRIMARY KEY (`id`),
KEY `userid` (`userid`),
CONSTRAINT `service_table_ibfk_1` FOREIGN KEY (`userid`) REFERENCES `user_table` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=141 DEFAULT CHARSET=utf8;
CREATE TABLE `user_table` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键',
`username` varchar(20) DEFAULT NULL COMMENT '姓名',
`phone` varchar(12) DEFAULT NULL COMMENT '手机号',
`creationTime` date DEFAULT NULL COMMENT '创建时间',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8;
还有两个是实体类我就不贴出来了,一个UserTable和一个ServiceTable;如果有需要jar的话可以私我