0
EmployeeDAOImpl.java (내 DAO 구현)입니다동안, 모든 DAO 세션 공장 또는 세션을 받고하는 것은 널
package com.crud.dao.implementations;
import java.util.List;
import javax.transaction.Transactional;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.resource.transaction.spi.TransactionStatus;
import org.springframework.stereotype.Repository;
import com.crud.dao.interfaces.EmployeeDAO;
import com.crud.model.Employee;
@Repository
public class EmployeeDAOImpl implements EmployeeDAO{
private SessionFactory sessionFactory;
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
@Transactional
public void insertSingleEmployee(Employee e) {
Session session = sessionFactory.getCurrentSession();
if(session!=null) {
try {
session.beginTransaction();
session.persist(e);
session.getTransaction().commit();
} catch (Exception e2) {
if(session.getTransaction().getStatus()== TransactionStatus.ACTIVE || session.getTransaction().getStatus()== TransactionStatus.MARKED_ROLLBACK) {
session.getTransaction().rollback();
}
}
finally {
session.close();
}
}
else {
System.out.println("session is null ");
}
}
@Transactional
public void updateSingleEmpployee(Employee e) {
Session session = this.sessionFactory.getCurrentSession();
try {
session.beginTransaction();
session.update(e);
session.getTransaction().commit();
} catch (Exception e2) {
if(session.getTransaction().getStatus()==TransactionStatus.ACTIVE || session.getTransaction().getStatus()== TransactionStatus.MARKED_ROLLBACK) {
session.getTransaction().rollback();
}
}
finally {
session.close();
}
}
@Transactional
public void deleteSingleEmployee(long employeeID) {
Session session = this.sessionFactory.getCurrentSession();
try {
session.beginTransaction();
Employee e = (Employee) session.load(Employee.class, new Long(employeeID));
if(e!=null)
session.delete(e);
session.getTransaction().commit();
} catch (Exception e) {
if(session.getTransaction().getStatus()== TransactionStatus.ACTIVE || session.getTransaction().getStatus()==TransactionStatus.MARKED_ROLLBACK) {
session.getTransaction().rollback();
}
}
finally {
session.close();
}
}
@SuppressWarnings("unchecked")
@Transactional
public List<Employee> listOfEmployees(){
Session session = this.sessionFactory.getCurrentSession();
List<Employee> listOfEmployees = null;
try {
session.beginTransaction();
listOfEmployees = session.createQuery("from Employee").list();
session.getTransaction().commit();
session.close();
} catch (Exception e) {
if(session.getTransaction().getStatus()== TransactionStatus.ACTIVE || session.getTransaction().getStatus()==TransactionStatus.MARKED_ROLLBACK) {
session.getTransaction().rollback();
}
}
finally {
session.close();
}
return listOfEmployees;
}
}
후 나의 봄 디스패처 XML 파일 spring_dispatcher-servlet.xml에
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
<context:component-scan base-package="com.crud.controllers" />
<context:annotation-config />
<mvc:annotation-driven />
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/pages/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
<bean id="myDataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://127.0.0.1:3306/university" />
<property name="username" value="root"></property>
<property name="password" value="root"></property>
</bean>
<bean id="mySessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource" ref="myDataSource" />
<property name="annotatedClasses">
<list>
<value>com.crud.model.Employee</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
<prop key="hibernate.c3p0.min_size">5</prop>
<prop key="hibernate.c3p0.max_size">30</prop>
<prop key="hibernate.c3p0.timeout">60</prop>
<prop key="hibernate.hbm2ddl.auto">create</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<bean id="employeeDao" class="com.crud.dao.implementations.EmployeeDAOImpl">
<property name="sessionFactory" ref="mySessionFactory" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager"/>
<bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="mySessionFactory" />
</bean>
</beans>
이 내 컨트롤러 클래스 EmployeeController.java
package com.crud.controllers;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.crud.dao.DAOFactory;
import com.crud.model.Employee;
@Controller
@ControllerAdvice
@RequestMapping(value="/employee")
public class EmployeeController {
@RequestMapping(value="/addPerson", method=RequestMethod.GET)
public String addForm() {
return "addPerson";
}
@RequestMapping(value="/save", method=RequestMethod.POST)
public String addEmployee(@ModelAttribute("employee") Employee e, BindingResult result) {
if(result.hasErrors())
return "addPerson";
else {
DAOFactory mysqlFactory = DAOFactory.getDAOFactory(1);
if(e!=null)
mysqlFactory.getEmployeeDAO().insertSingleEmployee(e);
}
return "hello";
}
}
와 일이다 내 엔티티 클래스 직원
package com.crud.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
@Entity
@Table(name="employee")
public class Employee {
@Id
@Column(name="id")
@GeneratedValue(strategy=GenerationType.IDENTITY)
private long id;
private String firstName;
private String lastName;
private String mobile;
private String address;
private String gender;
private String email;
public Employee() {
}
public Employee(long id, String firstName, String lastName, String mobile, String address, String gender,
String email) {
super();
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
this.mobile = mobile;
this.address = address;
this.gender = gender;
this.email = email;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
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 getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
[이 데이터베이스에 직원 엔티티 클래스에 대한 브라우저에서 사용자가 작성 양식의 세부 사항을 저장하는 동안 나는 점점 오전 오류입니다. 그러나 널 포인터 예외가 발생합니다. ][1]
최대 절전 모드 CFG 파일 설정은 여기
<property name="hibernate.connection.driver_class">com.mysql.cj.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://127.0.0.1:3306/school_driver</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">root</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>
<property name="hibernate.show_sql">true</property>
<property name="hibernate.format_sql">true</property>
<property name="hibernate.connection.autocommit">false</property>
<property name="hibernate.current_session_context_class">thread</property>
<property name="hibernate.hbm2ddl.auto">validate</property>
및 세션 공장 생성을위한 내 구성입니다
StandardServiceRegistry standardServiceRegistry = new StandardServiceRegistryBuilder().configure("hibernate.cfg.xml").build();
Metadata metadata = new MetadataSources(standardServiceRegistry).getMetadataBuilder().build();
hibernateSessionFactory = metadata.getSessionFactoryBuilder().build();
return hibernateSessionFactory;
친애하는 형제 나는 세션 팩토리를 구성하기 위해 주석을 사용하지 않았습니다. 내가 setter 메서드 주입 (당신은 봄 XML 파일 loook 수 있습니다) –
다음 XML 파일에서 args 전달 http://www.byteslounge.com/tutorials/spring-dependency-injection-with-xml-example –
나는 내 이제 질문을하면 더 많은 것을 이해할 수 있습니다. –