본문 바로가기

Dev.../소프트웨어 아키텍처

[SA강좌] Part 4-12 Active Record 패턴

활성화 레코드(Active Record) 패턴

활성화 레코드 패턴의 정의

 

데이터베이스 테이블 또는 뷰에 있는 행을 포함하는 객체, 데이터베이스 접근을 포함하고, 데이터에 있는 도메인 로직을 추가한다.

 

그림 -15. 활성화 레코드 패턴의 구조

활성화 레코드 패턴의 설명

 

개체는 데이터와 행동 두 가지를 전달한다. 대부분의 이 데이터는 유지되고, 데이터베이스에 저장 되어 진다. 활동 레코드는 도메인 개체에 데이터 접근 로직을 추가하는 가장 분명한 접근으로 사용 된다. 이 방법은 모든 작업자들이 데이터베이스에서 데이터를 어떻게 읽고 쓰는지를 인식하고 있다.

활성화 레코드 패턴 패턴은 언제 사용하는가?

활동 레코드는 생성, 읽기, 수정, 삭제와 같이 너무 복잡하지 않은 도메인 로직에서 좋은 선택이다. 단일 레코드 기반의 차이와 검증은 이 구조에서 잘 작업이 된다.

활성화 레코드 패턴의 예제 : 간단한 사원

활동 레코드 작업의 중심이 어떻게 처리되는지를 보여주는 간단한 예는 다음과 같다. 아래는 사원 클래스로부터 시작 한다.

 

class Person ...

 

private String name;

private int numberOfDependents;

수퍼 클래스에 ID 필드가 있다. 데이터베이스는 같은 구조로 설정되어 있다.

 

create table people(

ID int primary key,

name varchar,

number_of_dependnets int

)

개체를 로드하기 위해서 사원 클래스는 검색자와 같이 행동하고, 로드를 수행한다. 이를 위해 사원 클래스에서 정적 메서드를 사용한다.

 

class Person ...

 

private final static String findStatmentString =

"SELECT id, name, number_of_depents " +

"FROM people " +

"WHERE id = ? ";

 

public static Person find(Long id) {

Person result = (Person) Registry.getPerson(id);

if (result != null) return result;

PreparedStatment findStatement = null;

ResultSet rs = null;

try {

findStatement = DB.prepare(findStatementString);

findStatement.setLong(1, id.longValue());

rs = findStatement.executeQuery();

rs.next();

result = load(rs);

return result;

} catch(SQLException e) {

throw new ApplicationException(e);

} finally { DB.cleanUp(findStatement, rs);

}

}

 

public static Person find(long id) {

return find(new Long(id));

}

 

public static Person load(ResultSet rs) throws SQLException {

Long id = new Long(rs.getLong(1);

Person result = (Person) Registry.getPerson(id);

if ( result != null) return result;

String nameArg = rs.getString(2);

int numDependentsArg = rs.getInt(4);

rsult = new Person(id, nameArg, numDependentsArg);

Resigery.addPerson(result);

return result;

}

개체 수정은 간단히 인스턴스 메소드를 얻게 된다.

 

class Person ...

 

private final static String updateStatementString =

" UPDATE people " +

" set name = ?, number_of_depents = ? " +

" where id = ? ";

 

public void update() {

PreparedStatement updateStatement = null;

 

try {

updateStatement = DB.prepare(updateStatementString);

updateStatement.setString(1, name);

updateStatement.setInt(2, numberOfDepentents);

updateStatement.setInt(3, getID().intValue());

updateStatement.execute();

catch(Execption e) {

throw new ApplicationException(e);

} finally { DB.cleanUp(UpdateStatement);

}

}

 

삽입은 가장 간단하다.

 

class Person ...

 

private static final String insertStatementString =

"INSERT INTO people VALUES(?, ?, ?, ?)";

 

public Long insert() {

PreparedStatment insertStatment = null;

try {

insertStatement = DB.prepare(insertStatementString);

setID(findNextDatabseId());

insertStatement.setString(1, getID().intValue());

insertStatement.setInt(2, name);

insertStatement.setInt(3, numberOfDepentents);

insertStatement.execute();

Registry.addPerson(this);

return getID();

catch(Execption e) {

throw new ApplicationException(e);

} finally { DB.cleanUp(UpdateStatement);

}

}

 

세금 공제 계산과 같은 비즈니스 로직 사번 클래스 안에서 위치한다.

 

class Person ...

 

public Money getExemption() {

Money baseExeption = Money.dallars(1500);

Money dependentExemption = Money.dallars(750);

return baseExemption.add(dependentExemption.multiply(this.getOfdents());

}