SpringBoot+Hibernates使用封装Dao

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/nzzl54/article/details/81136654

这里结合一个查询的例子来演示,主要例子中使用了createSQLQuery(Sql)方法,Hql暂时不做介绍,现在先使用原生Sql来查询数据库已有的数据。数据库数据和效果图如下:

1、先封装一个BaseDao用于一些基础数据库的操作,请参考来自:

https://blog.csdn.net/haozhishang/article/details/53337973#commentBox

@Repository("baseDao")
public interface BaseDao{ 
/**	
	 * <b>function:</b>提供session使用
	 * @createDate 2016-11-25 下午03:39:22
	 * @author ending
	 * @return Session
	 * */
	public Session session();
	/**	
	 * <b>function:</b>提供HibernateTemplate使用
	 * @createDate 2016-11-25 下午03:39:22
	 * @author ending
	 * @return HibernateTemplate
	 * */
	public HibernateTemplate getTemplate();
   /**
	 * 通过SQL查询
	 * @param hql
	 * @return
	 * @throws Exception
	 */
	public <T> List<T> findBySql(String sql) throws Exception;

    //其他封装方法略,请参考上面链接
}

2、写实现类BaseDaoImpl,注意这里需要一些参数,否则会报错,之前写的文章有,请看:springboot上使用hibernate报错总结

@SuppressWarnings("unchecked")
@Transactional
@Repository("baseDaoImpl")
public class BaseDaoImpl extends HibernateDaoSupport implements BaseDao{
	@Autowired 
    public void setSessionFactoryOverride(SessionFactory sessionFactory)
    { 
      super.setSessionFactory(sessionFactory); 
    }

	@Override
	public Session session()
	{
		return this.currentSession();
	}

	@Override
	public HibernateTemplate getTemplate()
	{
		return this.getHibernateTemplate();
	}
	
	
	@Override
	public <T> List<T> findBySql(String Sql) throws Exception {
		// TODO Auto-generated method stub
		try{
			return session().createSQLQuery(Sql).list();
		}catch (Exception e){
			throw new RuntimeException(e);
		}
	}
}

3、基类定义完毕后,写需要使用的Dao和其实现类,TestVo为Entity类,对应数据库的表和字段的实体。

@Repository("modelTestDao")
public interface ModelTestDao {
	
	//通过SQL语句查询
	public List<TestVo> findByName(String name);
}
@Transactional
@Repository("modelTespDaoImpl")
public class ModelTestDaoImpl implements ModelTestDao{
	@Autowired
	private BaseDao baseDao;

	public BaseDao getBaseDao()
	{
		return baseDao;
	}

	@Override
	public List<TestVo> findByName(String name) {
		// TODO Auto-generated method stub
		String Sql = "select * from testdb.dbo.userinfo where name = '"+name+"'";
		try {
			return baseDao.findBySql(Sql);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
	}

}

4、写Controller和前端页面映射

@Controller
@RequestMapping("/test")
public class ModelController {
	protected final static Logger logger = LoggerFactory.getLogger(ModelController.class);

	@Autowired
	private ModelTestDao modelTestDao;

    @GetMapping("/index")
    public String index() {
        return "/modelhtml/NewFile";
    }
	
	@RequestMapping("/testQueryByName")
	@ResponseBody
    public Map<String,Object> testQueryByName(@RequestBody String name) {
		Map<String,Object> m = new HashMap<>();
		try {
			List<TestVo> list = (List<TestVo>) modelTestDao.findByName(name);
			System.err.println("sample started. data ="+list);
			
			if(list != null && list.size() > 0) {
				m.put("ok", "查询成功");
				m.put("data",list); 
			}else {
				m.put("error", "查询成功-不存在该用户");
				m.put("data",""); 
			}
			
		}catch(Exception e) {
			e.printStackTrace();
			logger.info(e.getStackTrace().toString());
			m.put("error",e.getStackTrace().toString());
		}
		return m;
    }
}
<script>
function testQueryByName(){
	var ffmap = {};
	//获取input的value
	var name = document.getElementById("text_name").value;
	$.ajax({
		type:"post",
		url:"/test/testQueryByName",
		data:name,
	    //data:JSON.stringify(ffmap),
		dataType:"json",
		contentType: "application/json; charset=utf-8",
		success:function(data){
			//var d = eval(data);
			ffmap = data;
			if(ffmap.ok != undefined){
				alert("测试 = "+JSON.stringify(ffmap.data));
			}else{
				alert(ffmap.error);
			} 
		}
	});
}

/*]]>*/
</script>

NewFile.html具体的代码就不给出了,input和button应该都会添加的,只要注意要引入JQ的路径就好(因为有用到Ajax)。

猜你喜欢

转载自blog.csdn.net/nzzl54/article/details/81136654