hibernate.cfg.xml
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- Database connection settings -->
<property name="connection.driver_class">oracle.jdbc.OracleDriver</property>
<property name="connection.url">jdbc:oracle:thin:@127.0.0.1:1521:xe</property>
<property name="connection.username">java</property>
<property name="connection.password">1111</property>
<property name="dialect">org.hibernate.dialect.Oracle10gDialect</property>
<!-- <property name="dialect">org.hibernate.dialect.DerbyDialect</property> -->
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>
<!-- Enable Hibernate's current session context -->
<property name="current_session_context_class">thread</property>
<!-- Disable the second-level cache -->
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<property name="hbm2ddl.auto">create</property>
<!--
매핑되야 정상이 인데 매핑이 안된다.
따라서
onfiguration cfg = new Configuration().configure(configFile)
.addAnnotatedClass(MemoDTOH.class);
설정 했다
<mapping class="memo.dto.MemoDTOH"/>
-->
</session-factory>
</hibernate-configuration>
HibernateManager
package config;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import memo.dto.MemoDTOH;
import sqlmap.MybatisManager;
public class HibernateManager {
private static SessionFactory sessionFactory;
private static String configFile = "hibernate.cfg.xml";
static { //클래스가 로딩도리 때 자동으로 실행되는 코드
try {
Configuration cfg = new Configuration().configure(configFile)
.addAnnotatedClass(MemoDTOH.class);
StandardServiceRegistryBuilder sb = new StandardServiceRegistryBuilder();
sb.applySettings(cfg.getProperties());
StandardServiceRegistry standardServiceRegistry = sb.build();
//SessionFactory 객체가 생성됨
sessionFactory = cfg.buildSessionFactory(standardServiceRegistry);
} catch (Throwable th) {
System.out.println("Enitial SessionFactory creation failed" + th);
throw new ExceptionInInitializerError(th);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
public void shutdown() {
sessionFactory.close();
}
}
class MemoController
package memo;
import java.io.IOException;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import member.MemberDTO;
import memo.dao.MemoDAO;
import memo.dao.MemoDAOH;
import memo.dto.MemoDTO;
import memo.dto.MemoDTOH;
//url mapping(현재 클래스외 url 을 연결시킴)
@WebServlet("/memo_servlet/*")
public class MemoController extends HttpServlet {
private static final long serialVersionUID = 1L;
//get 방식 호출
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//사용자가 요청한 url 정보에 따라 분기
String url =request.getRequestURL().toString();
//dao 객체 생성
MemoDAO dao=new MemoDAO();
MemoDAOH daoH=new MemoDAOH();
if(url.indexOf("insert.do")!=-1){
// MemoDTO dto=new MemoDTO();
// dto.setWriter(request.getParameter("writer"));
// dto.setMemo(request.getParameter("memo"));
// dao.insertMemo(dto);
MemoDTOH dto=new MemoDTOH();
dto.setWriter(request.getParameter("writer"));
dto.setMemo(request.getParameter("memo"));
daoH.insertMemo(dto);
}else if(url.indexOf("list.do")!=-1){
String search=request.getParameter("search");
String searchKey=request.getParameter("searchKey");
//메모 목록이 리턴됨
//List<MemoDTO> list=null;
List<MemoDTOH> list=null;
list =daoH.listMemo(searchKey, searchKey);
//출력 페이지에서 공유할 변수 저장
request.setAttribute("list", list);
//페이지 이동(포워딩)
String page="/memo/memo_list.jsp";
RequestDispatcher rd=
request.getRequestDispatcher(page);
rd.forward(request, response);
}else if(url.indexOf("view.do")!=-1){
int idx=Integer.parseInt(request.getParameter("idx"));
//MemoDTO dto =dao.viewMemo(idx); //레코드 1개 린턴
MemoDTOH dto=daoH.viewMemo(idx);
request.setAttribute("dto", dto);
//출력 페이지로 포워딩
String page="/memo/memo_view.jsp";
RequestDispatcher rd
=request.getRequestDispatcher(page);
rd.forward(request, response);
}else if(url.indexOf("del.do")!=-1){
//삭제할 번호
int idx=Integer.parseInt(request.getParameter("idx"));
//dao 에 삭제 요청
//dao.deleteMemo(idx);
daoH.deleteMemo(idx);
//페이지 이동
String page=request.getContextPath()+"/memo/memo.jsp";
response.sendRedirect(page);
}else if(url.indexOf("delete_all.do")!=-1){
//체크되 체크박스값들이 배열로 넘어옴
String[] idx=request.getParameterValues("idx");
//모두 체크가 안된 경우는 null로 넘어옴
if(idx!=null){
for(String num : idx){
//dao.deleteMemo(Integer.parseInt(num));
daoH.deleteMemo(Integer.parseInt(num));
}
}
String page=request.getContextPath()+"/memo/memo.jsp";
response.sendRedirect(page);
}else if(url.indexOf("update.do")!=-1){
//MemoDTO dto=new MemoDTO();
MemoDTOH dto=new MemoDTOH();
dto.setIdx(Integer.parseInt(request.getParameter("idx")));
dto.setMemo(request.getParameter("memo"));
dto.setWriter(request.getParameter("writer"));
daoH.updateMemo(dto);
String page=request.getContextPath()+"/memo/memo.jsp";
response.sendRedirect(page);
}
}
//post 방식 호출
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
MemoDAOH
package memo.dao;
import java.util.List;
import org.hibernate.Session;
import config.HibernateManager;
import memo.dto.MemoDTOH;
public class MemoDAOH {
public List<MemoDTOH> listMemo(String searchKey, String search){
List<MemoDTOH> list=null;
Session session=null;
try{
session=HibernateManager.getSessionFactory().openSession();
String sql="select idx, writer, memo, post_date from memo ";
if(searchKey.equals("writer_memo")){//이름 or 메모
sql +=" where writer like :search or memo like :search ";
}else{
sql +="where " +searchKey + " like :search";
}
sql += " order by idx desc ";
list=session.createNativeQuery(sql, MemoDTOH.class)
.setParameter("search", "%"+search+"%")
.getResultList();
}catch(Exception e){
e.printStackTrace();
}finally{
if(session!=null)session.close();
}
return list;
}
public void insertMemo(MemoDTOH dto){
//hibernate 실행 객체 생성
Session session=
HibernateManager.getSessionFactory().openSession();
//insert, delete, update 에는 트랜잭션 처리
session.beginTransaction(); // 트랜잭션 시작
//insert SQL 구문이 자동으로 작성되어 호출됨
session.save(dto);
session.getTransaction().commit();//커밋
session.close();// 세션 닫기
}
public void deleteMemo(int idx){
Session session=
HibernateManager.getSessionFactory().openSession();
//get(매퍼클래스, 키값) 레코드를 조회
// select * from memo where idx=5;
session.beginTransaction();
MemoDTOH dto=(MemoDTOH)session.get(MemoDTOH.class, idx);
session.delete(dto); // 레코드가 삭제됨
session.getTransaction().commit();
session.close();
}
public MemoDTOH viewMemo(int idx){
Session session=HibernateManager.getSessionFactory().openSession();
//select * from memo where idx=?
//키값으로 레코드를 조회하여 리턴
MemoDTOH dto=(MemoDTOH)session.get(MemoDTOH.class, idx);
session.close();
return dto;
}
public void updateMemo(MemoDTOH dto){
Session session=
HibernateManager.getSessionFactory().openSession();
session.beginTransaction();
//update memo set writer=?, memo=? where idx=?
//session.update(dto);
String sql=
"update memo set writer=:writer, memo=:memo "
+ " where idx=:idx";
session.createNativeQuery(sql, MemoDTOH.class)
.setParameter("writer", dto.getWriter())
.setParameter("memo", dto.getMemo())
.setParameter("idx", dto.getIdx())
.executeUpdate();
session.getTransaction().commit();
session.close();
}
}
MemoDTOH
package memo.dto;
import java.util.Date;
import javax.persistence.*;
import org.hibernate.annotations.CreationTimestamp;
//현재 클래스가 테이블과 매핑되는 클래스임을 알려줌
@Entity
@Table(name="memo") //memo 테이블과 매핑됨
public class MemoDTOH {
@Id //primary key
//자동생성 컬럼
//GenerationType.AUTO mysql 의 경우 또는 잘 모를 경우
// 오라클경우에도 AUTO 설정시 자동으로 처리
//strategy=GenerationType.SEQUENCE 오라클의 경우
@GeneratedValue(strategy=GenerationType.SEQUENCE)
@Column(name="IDX")//클래스의 변수와 테이블의 필드 매핑
private int idx;
@Column(name="WRITER")
private String writer;
@Column(name="MEMO")
private String memo;
@CreationTimestamp//타임스탬프생성
@Temporal(TemporalType.TIMESTAMP)//시스템의 현재 시간
@Column(name="POST_DATE")
private Date post_date;//java.util.Date
public MemoDTOH() {
}
public int getIdx() {
return idx;
}
public void setIdx(int idx) {
this.idx = idx;
}
public String getWriter() {
return writer;
}
public void setWriter(String writer) {
this.writer = writer;
}
public String getMemo() {
return memo;
}
public void setMemo(String memo) {
this.memo = memo;
}
public Date getPost_date() {
return post_date;
}
public void setPost_date(Date post_date) {
this.post_date = post_date;
}
@Override
public String toString() {
return "MemoDTOH [idx=" + idx + ", writer=" + writer + ", memo=" + memo + ", post_date=" + post_date + "]";
}
}
댓글 ( 4)
댓글 남기기