hibernate一个注册小例子

  1 package com.briup.common;
  2 
  3 import org.hibernate.Session;
  4 import org.hibernate.SessionFactory;
  5 import org.hibernate.cfg.Configuration;
  6 
  7 @SuppressWarnings("deprecation")
  8 public class HibernateSessionFactory {
  9     private static SessionFactory factory;
 10     private static final ThreadLocal<Session> threadLocal=new ThreadLocal<Session>();
 11     private HibernateSessionFactory(){}
 12     static {
 13         Configuration config=new Configuration();
 14         config.configure();
 15         factory=config.buildSessionFactory();
 16     }
 17     public static Session getSession(){
 18         Session session=threadLocal.get();
 19         if(session==null){
 20             session=factory.openSession();
 21             threadLocal.set(session);
 22         }
 23         return session;
 24     }
 25 }
 26 create table student(
 27     id int(10) primary key,
 28     name varchar(20),
 29     age int(3),
 30     gender varchar(2),
 31     hobby varchar(20),
 32     course varchar(2),
 33     description varchar(200)
 34 );
 35 alter table student add password varchar(20) after name;
 36 alter table student modify id int(10) auto_increment;
 37 package com.briup.bean;
 38 
 39 import java.io.Serializable;
 40 
 41 // 编码,用户名,年龄,性别,爱好,学习方向,个人简介
 42 public class Student implements Serializable{
 43     /**
 44      * 
 45      */
 46     private static final long serialVersionUID = -8169238824872484701L;
 47     private Long id;//这里使用包装类型,可以避免用户给你的值是null的时候发生错误
 48     private String username;
 49     private String password;
 50     private Integer age;
 51     private Character gender;
 52     private String hobby;
 53     private String course;
 54     private String description;
 55     public Long getId() {
 56         return id;
 57     }
 58     public void setId(Long id) {
 59         this.id = id;
 60     }
 61     public Student(Long id, String username,String password,Integer age, Character gender,
 62             String hobby, String course, String description) {
 63         super();
 64         this.id = id;
 65         this.username = username;
 66         this.age = age;
 67         this.gender = gender;
 68         this.hobby = hobby;
 69         this.course = course;
 70         this.description = description;
 71     }
 72     public Student() {
 73         super();
 74     }
 75     public String getUsername() {
 76         return username;
 77     }
 78     public void setUsername(String username) {
 79         this.username = username;
 80     }
 81     public Integer getAge() {
 82         return age;
 83     }
 84     public void setAge(Integer age) {
 85         this.age = age;
 86     }
 87     public Character getGender() {
 88         return gender;
 89     }
 90     public void setGender(Character gender) {
 91         this.gender = gender;
 92     }
 93     public String getHobby() {
 94         return hobby;
 95     }
 96     public void setHobby(String hobby) {
 97         this.hobby = hobby;
 98     }
 99     public String getCourse() {
100         return course;
101     }
102     public void setCourse(String course) {
103         this.course = course;
104     }
105     public String getDescription() {
106         return description;
107     }
108     public void setDescription(String description) {
109         this.description = description;
110     }
111     public void setPassword(String password) {
112         this.password = password;
113     }
114     public String getPassword() {
115         return password;
116     }
117     
118 }
119 <?xml version="1.0"?>
120 <!DOCTYPE hibernate-mapping PUBLIC
121         "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
122         "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
123 
124 <hibernate-mapping package="com.briup.bean">
125     <class name="Student" table="STUDENT">
126         <id name="id" column="ID">
127             <generator class="native" />
128         </id>
129         <property name="username"/>
130         <property name="password"/>
131         <property name="age"/>
132         <property name="gender"/>
133         <property name="hobby"/>
134         <property name="course"/>
135         <property name="description"/>
136     </class>
137 </hibernate-mapping>
138 <?xml version='1.0' encoding='utf-8'?>
139 <!DOCTYPE hibernate-configuration PUBLIC
140         "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
141         "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
142 
143 
144 <hibernate-configuration>
145 
146     <session-factory>
147 
148         <!-- Database connection settings -->
149         <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
150         <property name="connection.url">jdbc:mysql://127.0.0.1:3306/briup</property>
151         <property name="connection.username">guodaxia</property>
152         <property name="connection.password">961012gz</property>
153 
154         <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
155         <property name="show_sql">true</property>
156 
157         <mapping resource="com/briup/bean/Student.hbm.xml"/>
158 
159     </session-factory>
160 
161 </hibernate-configuration>
162 package com.briup.dao;
163 
164 import org.hibernate.Session;
165 
166 import com.briup.bean.Student;
167 
168 public interface IStudentDao {
169     public Session getSession();
170     public void addStudent(Student student);
171     public Student getStudentByName(String name);
172 }
173 package com.briup.service;
174 
175 import com.briup.bean.Student;
176 
177 public interface IstudentService {
178     public Student login(String name,String pwd);
179     public void register(Student stu);
180 }
181 package com.briup.dao.impl;
182 
183 import java.util.List;
184 
185 import org.hibernate.Query;
186 import org.hibernate.Session;
187 
188 import com.briup.bean.Student;
189 import com.briup.common.HibernateSessionFactory;
190 import com.briup.dao.IStudentDao;
191 @SuppressWarnings("unchecked")
192 public class StudentDaoImpl implements IStudentDao{
193 
194     public Session getSession() {
195         return HibernateSessionFactory.getSession();
196     }
197 
198     public void addStudent(Student student) {
199         getSession().beginTransaction();
200         try{
201             getSession().save(student);
202             getSession().getTransaction().commit();
203         }catch(Exception e){
204             getSession().getTransaction().rollback();
205             e.printStackTrace();
206         }
207         
208     }
209 
210     public Student getStudentByName(String name) {
211         getSession().beginTransaction();
212         try{
213             String hql="from Student where name=?";
214             Query query=getSession().createQuery(hql);
215             query.setString(0, name);
216             List<Student> list=query.list();
217             getSession().getTransaction().commit();
218             if(list.size()>0){
219                 return list.get(0);
220             }
221         }catch(Exception e){
222             getSession().getTransaction().rollback();
223             e.printStackTrace();
224         }
225         return null;
226     }
227 
228 }
229 
230 package com.briup.service.impl;
231 
232 import com.briup.bean.Student;
233 import com.briup.dao.IStudentDao;
234 import com.briup.dao.impl.StudentDaoImpl;
235 import com.briup.service.IstudentService;
236 
237 public class StudentServiceImpl implements IstudentService{
238     private IStudentDao stuDao;
239     public StudentServiceImpl(StudentDaoImpl stuDao){
240         this.stuDao=stuDao;
241     }
242     public Student login(String name, String pwd) {
243         Student s=stuDao.getStudentByName(name);
244         if(s==null)    return null;
245         return s.getPassword().equals(pwd)?s:null;
246     }
247 
248     public void register(Student stu) {
249         stuDao.addStudent(stu);
250     }
251 }
252 package com.briup.web;
253 
254 import java.io.IOException;
255 import java.util.Arrays;
256 
257 import javax.servlet.ServletException;
258 import javax.servlet.http.HttpServlet;
259 import javax.servlet.http.HttpServletRequest;
260 import javax.servlet.http.HttpServletResponse;
261 
262 import com.briup.bean.Student;
263 import com.briup.dao.impl.StudentDaoImpl;
264 import com.briup.service.IstudentService;
265 import com.briup.service.impl.StudentServiceImpl;
266 
267 public class RegistServlet extends HttpServlet{
268 
269     /**
270      * 
271      */
272     private static final long serialVersionUID = 2226750325614186979L;
273     
274     @Override
275     protected void doGet(HttpServletRequest req, HttpServletResponse resp)
276             throws ServletException, IOException {
277         doPost(req, resp);
278     }
279     
280     @Override
281     protected void doPost(HttpServletRequest req, HttpServletResponse resp)
282             throws ServletException, IOException {
283         req.setCharacterEncoding("UTF-8");
284         resp.setCharacterEncoding("UTF-8");
285         
286         String username=req.getParameter("username");
287         String password=req.getParameter("password");
288         String arr[]=req.getParameterValues("hobby");
289         String hobby=Arrays.toString(arr);
290         
291         Student stu=new Student();
292         stu.setUsername(username);
293         stu.setPassword(password);
294         stu.setHobby(hobby);
295         
296         IstudentService service=new StudentServiceImpl(new StudentDaoImpl());
297         service.register(stu);
298         
299         req.getRequestDispatcher("/success.html").forward(req, resp);
300     }
301 }
302 <?xml version="1.0" encoding="UTF-8"?>
303 <web-app version="2.5" 
304     xmlns="http://java.sun.com/xml/ns/javaee" 
305     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
306     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
307     http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
308   <display-name></display-name>    
309   <welcome-file-list>
310     <welcome-file>index.jsp</welcome-file>
311   </welcome-file-list>
312   
313   <servlet>
314       <servlet-name>RegistServlet</servlet-name>
315       <servlet-class>com.briup.web.RegistServlet</servlet-class>
316   </servlet>
317   <servlet-mapping>
318       <servlet-name>RegistServlet</servlet-name>
319       <url-pattern>/regist</url-pattern>
320   </servlet-mapping>
321   
322 </web-app>
323 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
324 <html>
325   <head>
326     <title>regist.html</title>
327     
328     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
329     <meta http-equiv="description" content="this is my page">
330     <meta http-equiv="content-type" content="text/html; charset=UTF-8">
331     
332     <!--<link rel="stylesheet" type="text/css" href="./styles.css">-->
333 
334   </head>
335   
336   <body>
337     <form action="regist" method="get">
338         <input type="text" name="username"><br/>
339         <input type="password" name="password"><br/>
340         <input type="checkbox" name="hobby" value="打篮球">打篮球
341         <input type="checkbox" name="hobby" value="看小说">看小说
342         <input type="checkbox" name="hobby" value="玩网游">玩网游
343         <input type="submit" value="注册">
344     </form>
345   </body>
346 </html>
347 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
348 <html>
349   <head>
350     <title>MyHtml.html</title>
351     
352     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
353     <meta http-equiv="description" content="this is my page">
354     <meta http-equiv="content-type" content="text/html; charset=UTF-8">
355     
356     <!--<link rel="stylesheet" type="text/css" href="./styles.css">-->
357 
358   </head>
359   
360   <body>
361   <center>  注册成功!</center><br/>
362     <a href="javascript:history.go(-1);">返回登录页面</a>
363   </body>
364 </html>
View Code

 这个代码中事务处理放错位置了,应该放在service的实现类中

posted @ 2016-07-14 15:23  guodaxia  阅读(340)  评论(0编辑  收藏  举报