2015-05-30 74 views
2

我是在spring和hibernate中新建的,所有的東西都正常工作,但是我在每次調用getCurrentSession時都檢查了一個新的連接線程已經在mysql中進入休眠狀態。據我所知這不是一個好的數據庫實踐。爲什麼getCurrentSession每次都創建新的連接線程。 我的代碼 -getCurrentSession在每次調用時都創建新的連接

應用程序的context.xml

<?xml version="1.0" encoding="UTF-8"?> 
<beans xmlns="http://www.springframework.org/schema/beans" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" 
    xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" 
    xmlns:mvc="http://www.springframework.org/schema/mvc" 
    xsi:schemaLocation=" 
http://www.springframework.org/schema/beans 
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd 
http://www.springframework.org/schema/aop 
http://www.springframework.org/schema/aop/spring-aop-4.0.xsd 
http://www.springframework.org/schema/tx 
http://www.springframework.org/schema/tx/spring-tx-4.0.xsd 
http://www.springframework.org/schema/context 
http://www.springframework.org/schema/context/spring-context-4.0.xsd"> 

    <tx:annotation-driven /> 
    <context:component-scan base-package="com.vc.teacher" /> 


    <bean id="transactionManager" 
     class="org.springframework.orm.hibernate4.HibernateTransactionManager"> 
     <property name="sessionFactory" ref="sessionFactory"></property> 
    </bean> 

    <bean id="sessionFactory" 
     class="org.springframework.orm.hibernate4.LocalSessionFactoryBean" 
     lazy-init="false"> 
     <property name="dataSource" ref="dataSource" /> 
     <property name="annotatedClasses"> 
      <list> 
       <value>com.vc.teacher.entities.User</value> 
      </list> 
     </property> 
     <property name="hibernateProperties"> 
      <props> 
       <prop key="hibernate.dialect">org.hibernate.dialect.HSQLDialect</prop> 
       <!-- <prop key="hibernate.current_session_context_class">thread</prop> --> 
       <prop key="show_sql">true</prop> 
      </props> 
     </property> 
    </bean> 



    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"> 
     <property name="driverClassName" value="com.mysql.jdbc.Driver"></property> 
     <property name="url" value="jdbc:mysql://localhost:3306/teacher"></property> 
     <property name="username" value="root"></property> 
     <property name="password" value="root"></property> 
    </bean> 

    <bean id="userDao" class="com.vc.teacher.db.dao.UserDao"> 
     <property name="sessionFactory" ref="sessionFactory"></property> 
    </bean> 

</beans> 

userDAO的類

package com.vc.teacher.db.dao; 

import java.util.List; 

import org.hibernate.Query; 
import org.hibernate.Session; 
import org.hibernate.SessionFactory; 
import org.hibernate.Transaction; 
import org.springframework.beans.factory.annotation.Autowired; 
import org.springframework.transaction.annotation.Transactional; 

import com.vc.teacher.entities.User; 

public class UserDao { 


    @Autowired 
    SessionFactory sessionFactory; 

    public SessionFactory getSessionFactory() { 
     return sessionFactory; 
    } 

    public void setSessionFactory(SessionFactory sessionFactory) { 
     this.sessionFactory = sessionFactory; 
    } 

    @Transactional 
    public User checkCreditionals(String email, String password){ 
     User user = null; 
     Session session = sessionFactory.getCurrentSession(); 
     Query query = session.createQuery("from User where email = '"+email+"' and password = '"+password+"'"); 
     List list = query.list(); 
     if(list.size()>0) 
      user = (User)list.get(0); 

     return user; 
    } 

    @Transactional 
    public boolean registerUser(User user){ 
     boolean result = false; 
     Session session = sessionFactory.getCurrentSession(); 
     try{ 
      user.setUserTypeId(2); 
      session.save(user); 

      result = true; 
     } catch (Exception e){ 
      result = false; 
      e.printStackTrace(); 
     } 

     return result; 
    } 

} 

實體類 - 用戶

package com.vc.teacher.entities; 

import javax.persistence.Column; 
import javax.persistence.Entity; 
import javax.persistence.GeneratedValue; 
import javax.persistence.Id; 
import javax.persistence.Table; 

@Entity 
@Table(name="user") 
public class User { 

    @Id 
    @GeneratedValue 
    @Column(name="user_id") 
    private int id; 
    @Column(name="age") 
    private int age; 
    @Column(name="user_type_id") 
    private int userTypeId; 
    @Column(name="first_name") 
    private String firstName; 
    @Column(name="last_name") 
    private String lastName; 
    @Column(name="profession") 
    private String profession; 
    @Column(name="phone") 
    private String phone; 
    @Column(name="email") 
    private String email; 
    @Column(name="password") 
    private String password; 
    @Column(name="address") 
    private String address; 
    @Column(name="status") 
    private String status; 


    public int getId() { 
     return id; 
    } 
    public void setId(int id) { 
     this.id = id; 
    } 
    public int getAge() { 
     return age; 
    } 
    public void setAge(int age) { 
     this.age = age; 
    } 

    public int getUserTypeId() { 
     return userTypeId; 
    } 
    public void setUserTypeId(int userTypeId) { 
     this.userTypeId = userTypeId; 
    } 
    public String getFirstName() { 
     return firstName; 
    } 
    public void setFirstName(String firstName) { 
     this.firstName = firstName; 
    } 
    public String getLastName() { 
     return lastName; 
    } 
    public void setLastName(String lastName) { 
     this.lastName = lastName; 
    } 
    public String getProfession() { 
     return profession; 
    } 
    public void setProfession(String profession) { 
     this.profession = profession; 
    } 
    public String getPhone() { 
     return phone; 
    } 
    public void setPhone(String phone) { 
     this.phone = phone; 
    } 
    public String getEmail() { 
     return email; 
    } 
    public void setEmail(String email) { 
     this.email = email; 
    } 
    public String getPassword() { 
     return password; 
    } 
    public void setPassword(String password) { 
     this.password = password; 
    } 
    public String getAddress() { 
     return address; 
    } 
    public void setAddress(String address) { 
     this.address = address; 
    } 
    public String getStatus() { 
     return status; 
    } 
    public void setStatus(String status) { 
     this.status = status; 
    } 

} 

Controller類 - 的AccountController

package com.vc.teacher.controller; 

import org.springframework.context.ApplicationContext; 
import org.springframework.context.support.ClassPathXmlApplicationContext; 
import org.springframework.stereotype.Controller; 
import org.springframework.ui.Model; 
import org.springframework.web.bind.annotation.RequestMapping; 
import org.springframework.web.bind.annotation.RequestMethod; 
import org.springframework.web.bind.annotation.RequestParam; 
import org.springframework.web.servlet.ModelAndView; 
import org.springframework.web.servlet.mvc.support.RedirectAttributes; 

import com.vc.teacher.db.dao.UserDao; 
import com.vc.teacher.entities.User; 

@Controller 
public class AccountController { 

    @RequestMapping("/login") 
    public String loginUser(@RequestParam("email") String email, 
      @RequestParam("password") String password, Model model) { 
     ApplicationContext context = new ClassPathXmlApplicationContext(
       "applicationContext.xml"); 
     User user = ((UserDao) context.getBean("userDao")).checkCreditionals(
       email, password); 
     if (user != null) { 
      model.addAttribute("user", user); 
      return "jsp/profile"; 
     } else { 
      model.addAttribute("error", "Wrong creditionals"); 
      return "jsp/signin"; 
     } 

    } 

    @RequestMapping("/signUp") 
    public String initilize(Model model) { 
     model.addAttribute(new User()); 
     return "jsp/signup"; 
    } 

    @RequestMapping(method = RequestMethod.POST, value = "/register") 
    public String signUpUser(User user, RedirectAttributes attributes) { 
     boolean result = false; 

     ApplicationContext context = new ClassPathXmlApplicationContext(
       "applicationContext.xml"); 
     user.setStatus("Deactive"); 
     result = ((UserDao) context.getBean("userDao")).registerUser(user); 

     if (result == true) { 
      attributes.addFlashAttribute("message", "You are ready to go now !"); 
      return "redirect:/signUp"; 
     } else { 
      attributes.addFlashAttribute("message", "Something went wrong"); 
      return "redirect:/signUp"; 
     } 

    } 
} 

MySQL連接狀態快照是 -

enter image description here

回答

1

通過偵聽器使用部署描述符和以下條目加載上下文。

<listener> <listen-class>org.springframework.web.context.ContextLoaderListener </listener-class> </listener>

您已經定義了組件掃描包,所以你可以在這裏使用時自動連接,只需添加@Component註解到您的UserDAO並從服務層去掉下面的代碼

ApplicationContext context = new ClassPathXmlApplicationContext(
      "applicationContext.xml"); 
User user = ((UserDao) context.getBean("userDao")) 

定義帶有@Component註釋的DAO類。

package com.vc.teacher.db.dao; 

import java.util.List; 

import org.hibernate.Query; 
import org.hibernate.Session; 
import org.hibernate.SessionFactory; 
import org.hibernate.Transaction; 
import org.springframework.beans.factory.annotation.Autowired; 
import org.springframework.transaction.annotation.Transactional; 

import com.vc.teacher.entities.User; 
@Component 
public class UserDao { 


@Autowired 
SessionFactory sessionFactory; 

public SessionFactory getSessionFactory() { 
    return sessionFactory; 
} 

public void setSessionFactory(SessionFactory sessionFactory) { 
    this.sessionFactory = sessionFactory; 
} 

@Transactional 
public User checkCreditionals(String email, String password){ 
    User user = null; 
    Session session = sessionFactory.getCurrentSession(); 
    Query query = session.createQuery("from User where email = '"+email+"' and password = '"+password+"'"); 
    List list = query.list(); 
    if(list.size()>0) 
     user = (User)list.get(0); 

    return user; 
} 

@Transactional 
public boolean registerUser(User user){ 
    boolean result = false; 
    Session session = sessionFactory.getCurrentSession(); 
    try{ 
     user.setUserTypeId(2); 
     session.save(user); 

     result = true; 
    } catch (Exception e){ 
     result = false; 
     e.printStackTrace(); 
    } 

    return result; 
} 

}` 

現在開始喜歡這個 -

@Autowired 
UserDao userDao; 

的對象,然後調用你的方法 -

userDao.checkCreditionals(email, password); 
+0

我這樣做了,但在編譯時它給出了這個錯誤 - 沒有發現依賴性的[com.vc.teacher.db.dao.UserDao]類型的合格bean:預計至少有1個bean有資格作爲這個autowire候選者依賴。依賴註釋:{@ org.springframework.beans.factory.annotation.Autowired(required = true)} –

+0

確保您的UserDao類使用@Component進行註釋..因爲我們是隱式定義bean的。 –

+0

我已在UserDao類 –

3

你正在創建爲每個請求彈簧上下文:

ApplicationContext context = new ClassPathXmlApplicationContext(
       "applicationContext.xml"); 

Ť帽子應該只發生一次,當應用程序啓動時,在一個監聽器中。

看一看這裏: Loading context in Spring using web.xml

你也可能需要在控制器中注入的UserDAO。

+0

我做到了,但在編譯的時候它給這個錯誤 - 沒有合格豆類型爲[com.vc.teacher.db.dao.UserDao]的依賴項:預計至少有1個bean符合此依賴關係的自動連線候選。依賴註釋:{@ org.springframework.beans.factory.annotation.Autowired(required = true) –

+0

您已經在xml中聲明瞭userDao,因此應該可以工作。也許發佈您的更新解決方案 – Robert

+0

我已根據您的答案更改了代碼。請不要將代碼的其他部分相同。 –

相關問題