标签:hibernate 架构 事务 session xml
hibernate是数据层的架构,想必大家很熟了吧,话不多说,直接贴代码。
首先是hibernate.cfg.xml的配置,实际上这里就是数据库的配置:
<!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="connection.driver_class">com.mysql.jdbc.Driver</property> <property name="connection.url">jdbc:mysql://127.0.0.1:3306/test</property> <property name="connection.username">root</property> <property name="connection.password">123456</property> <property name="dialect">org.hibernate.dialect.MySQLDialect</property> <property name="show_sql">true</property> <property name="hbm2ddl.auto">update</property> <mapping resource="com/hibernate/entity/User.hbm.xml"/> </session-factory> </hibernate-configuration>
<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping package="com.hibernate.entity"><!-- package为class所在的包 --> <class name="User" table="user"> <id name="id" type="int"><!-- 这相当于@column,匹配数据库中的字段,进行daoimpl的操作 --> <generator class="native" /> </id> <property name="name" type="java.lang.String"> <column name="name" /> </property> <property name="password" type="java.lang.String"> <column name="password" /> </property> </class> </hibernate-mapping>
第一是LoginController:
/* * 这个类测试用 * * */ public class LoginController { public static void main(String[] args){ User user=new User(); user.setName("123"); user.setPassword("123"); LoginDao loginDao=new LoginDaoImpl(); User user2=loginDao.login(user);//调用登录方法 //打印取出的ID if(user2!=null){ System.out.println("id:"+user2.getId()); } } }
这种方式不好哦,这个测试比较简单才这么做。
public interface LoginDao { public User login(User user); }
public class LoginDaoImpl implements LoginDao{ private Session session; private static HibernateUtil hibernateUtil; //静态加载session工厂生产session类 static{ hibernateUtil=new HibernateUtil(); } public User login(User user) { User user2=new User(); session=hibernateUtil.getSession();//获得由session工厂生产的session Query query=session.createQuery("select u from User u"); List<User> list=query.list(); user2.setId(list.get(0).getId()); return user2; } }
public class User { private int id; private String name; private String password; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
这些东西仅供参考,感觉数据层的处理还是挺好用的,但单独用的话配置太繁琐,结合spring会好用很多。
标签:hibernate 架构 事务 session xml
原文地址:http://blog.csdn.net/u014274324/article/details/40085849