by-nc-sa     개발자, DBA가 함께 만들어가는 구루비 지식창고!

Spring + Hibernate CRUD 예제




1. Hibernate 라이브러리를 다운받는다.

  • pom.xml 에 dependency를 추가한다.
  • mvn eclipse:eclipse 명령어를 실행해서 hibernate 라이브러리를 다운로드 받는다.
    <dependency>  
            <groupId>org.hibernate</groupId>  
            <artifactId>hibernate-core</artifactId>  
            <version>4.1.7.Final</version>
    </dependency>
    

2. 테이블정보를 xml로 설정한다.

Emp.hbm.xml
<?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>
	<class name="com.oracleclub.study.mvc.model.Emp" table="Emp">
		<id name="empno" column="empno" type="java.lang.Integer"/>
		<property name="mgr" column="mgr" type="java.lang.Integer" not-null="false" />
		<property name="sal" column="sal" type="java.lang.Integer" not-null="false" />
		<property name="deptno" column="deptno" type="java.lang.String" not-null="false" />
		<property name="ename" column="ename" type="java.lang.String" not-null="false" />
		<property name="job" column="job" type="java.lang.String" not-null="false" />
		<property name="hiredate" column="hiredate" type="java.lang.String" not-null="false" />
	</class>
</hibernate-mapping>
com.oracleclub.study.mvc.model.Emp.java
@Entity
public class Emp {

	@Id
	int empno;
	
	@Column(length=100)
	int mgr;
	
	@Column(length=100)
	int sal;
	
	@Column(length=100)
	String deptno;
	
	@Column(length=100)
	String ename;
	
	@Column(length=100)
	String job;
	
	@Column(length=100)
	String hiredate;
	
	
	public Emp(int empno) {
		super();
		this.empno = empno;
	}


	public int getEmpno() {
		return empno;
	}


	public void setEmpno(int empno) {
		this.empno = empno;
	}


	public int getMgr() {
		return mgr;
	}


	public void setMgr(int mgr) {
		this.mgr = mgr;
	}


	public int getSal() {
		return sal;
	}


	public void setSal(int sal) {
		this.sal = sal;
	}


	public String getDeptno() {
		return deptno;
	}


	public void setDeptno(String deptno) {
		this.deptno = deptno;
	}


	public String getEname() {
		return ename;
	}


	public void setEname(String ename) {
		this.ename = ename;
	}


	public String getJob() {
		return job;
	}


	public void setJob(String job) {
		this.job = job;
	}


	public String getHiredate() {
		return hiredate;
	}


	public void setHiredate(String hiredate) {
		this.hiredate = hiredate;
	}
	public Emp(){
		
	}


	public Emp(int empno, int mgr, int sal, String deptno, String ename, String job, String hiredate) {
		this.empno = empno;
		this.mgr = mgr;
		this.sal = sal;
		this.deptno = deptno;
		this.ename = ename;
		this.job = job;
		this.hiredate = hiredate;
	}

	
}

3. spring 설정파일에 hibernate 설정을추가한다.

applicationContext-hibernate.xml
        <bean id="empBO" class="com.oracleclub.study.mvc.bo.EmpBO">
	</bean>

	<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
		<property name="dataSource" ref="dataSource" />
		<property name="mappingResources">
			<list>
				<value>com/oracleclub/study/mvc/model/Emp.hbm.xml</value>
			</list>
		</property>
		<property name="hibernateProperties">
			<props>
				<prop key="dialect">org.hibernate.dialect.MySQLDialect</prop>	
				<prop key="cache.provider_class">org.hibernate.cache.NoCacheProvider</prop>			
				<prop key="show_sql">true</prop>
				<prop key="hbm2ddl.auto">update</prop>
			</props>
		</property>
	</bean>
	
	<bean id="dataSource" class="org.springframework.jdbc.datasource.SimpleDriverDataSource">
		<property name="driverClass" value="com.mysql.jdbc.Driver" />
		<property name="url" value="jdbc:mysql://localhost:3306/mysql?characterEncoding=UTF-8" />
		<property name="username" value="couopang" />
		<property name="password" value="1234" />
	</bean>
	
	<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
		<property name="sessionFactory" ref="sessionFactory" />
	</bean>

web.xml에서 applicationContext-datasource.xml 파일을 로딩하도록 context-param 설정을 추가한다.

web.xml
<context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
            classpath:spring/applicationContext.xml      
            classpath:spring/applicationContext-hibernate.xml   
        </param-value>
    </context-param>    

4. Emp 리스트를 가져오는 EmpBO 구현한다.

com.oracleclub.study.mvc.bo.EmpBO.java
@Service("empBO")
public class EmpBO {
	@Resource
	private SessionFactory sessionFactory;
	
	public List<Emp> getAll(){
		Session session = sessionFactory.openSession();
		List<Emp> empList = (List<Emp>) session.createCriteria(Emp.class).list();
		return empList;
	}
        public void add(Emp emp){
		Session session = sessionFactory.openSession();
		session.save(emp);
		session.flush();
	}


}


5. EmpListController 에서 empBO에서 가져온 리스트를 view에 넘겨준다.

com.oracleclub.study.mvc.controller.EmpListController.java
    @Autowired
	private EmpBO empBO;
	
    @RequestMapping(value = "/emp/list")
    public ModelAndView list() {

        ModelAndView mv = new ModelAndView();

        // View 지정
        // mvc-dispatcher-servlet.xml 파일의 viewResolver를 사용
        mv.setViewName("emp/list");
        
        List<Emp> empList = empBO.getAll();
        mv.addObject("empList", empList);

        return mv;
    }

    @RequestMapping(value = "emp/register", method = RequestMethod.POST)
    public ModelAndView register(@ModelAttribute Emp emp) {
        // DB저장하고
    	empBO.add(emp);
        // View 설정
        ModelAndView mv = new ModelAndView();
        mv.setViewName("emp/view");

        return mv;
    }

    

문서정보

Enter labels to add to this page:
Please wait 
Looking for a label? Just start typing.