-----------------------------------------------------------首先在User.hbm.xml配置-------------------------------------------------------------
- <hibernate-mapping>
- <class table="usertable" name="model.User" >
- <cache usage="read-write"/>
- <id name="id" column="id" unsaved-value="0">
- <generator class="native"/>
- </id>
- <property name="userName" column="username" not-null="true"/>
- <property name="password" column="password" not-null="true"/>
- <!-- <property name="deptId" column="dept_id"/> -->
- <many-to-one name="dept" class="model.Dept" column="dept_id" />
- </class>
- <query name="findByUserId">
- <![CDATA[
- from User u where u.id=:id
- ]]>
- </query>//这个也可以写在class里面,但是写在这里要保证name是唯一的。
- //这里也可以写sql
- <sql-query name="findByUserName">
- <![CDATA[
- select useName from usertable u where u.passWord=:password
- ]]>
- </sql-query>
- </hibernate-mapping>
------------------------------------------------------------------dao层代码---------------------------------------------------------
- // 根据id查找用户
- public User findById(final Integer id)
- {
- // return (User)ht.get(User.class, id);
- return (User)ht.execute(new HibernateCallback()
- {
- public Object doInHibernate(Session session)
- throws HibernateException,
- SQLException
- {
- Query query = session.getNamedQuery("findByUserId");//这里findByUserId就是配置文件里的name值
- query.setInteger("id", id);
- User user = (User)query.uniqueResult();
- // 初始化
- Hibernate.initialize(user.getDept());//这里主要解决默认是延迟加载问题(报什么代理异常)。
- return user;
- }
- });
- }
-------------------------------------测试代码-----------------------------------------------------------------------------------
- public class TestNameQuery
- {
- public static void main(String[] args)
- {
- ApplicationContext context =
- new ClassPathXmlApplicationContext("applicationContext.xml");
- // 从容器中获取userService
- UserService userService = (UserService)context.getBean("userService");
- User user = userService.findById(1);
- System.out.println(user.getDept().getName());//延迟加载问题上面是一种解决方案,还可以在配置文件里lazy=“false”或者fetch=“select”
- }
- }