스프링 부트 기초 - 8(SessionScope, @Generated value)

1 minute read

JSTL SessionScope

  • 브라우저가 최초의 요청을 발생 시키고 브라우저를 닫을 때 까지를 SessionScope라고 부른다.
  • SessionScope 에서는 session 영역에 저장되어 있는 데이터나 객체를 자유롭게 사용할 수 있다.
  • Controller에서 view로 안보내도 사용 가능


▶ UserApiController

@PostMapping(value = "/api/user/login")
public ResponseDto<Integer> login(@RequestBody User user, HttpSession session) {
	User principal = userService.로그인(user); // principal(접근주체)

	if(principal != null) {	// 세션 만들기
		System.out.println("로그인 성공");
		session.setAttribute("principal", principal);
	}
	return new ResponseDto<Integer>(HttpStatus.OK.value(),1);
}

setAttribute를 활용해서 세션의 값을 맵핑 해준다.


▶ LoginForm

${empty SessionScope.principal}

위와 같이 JSTL을 활용하여 SessionScope에 principal의 유무를 판별할 수 있다.

@Generated value

@GeneratedValue(strategy = GenerationType.IDENTITY)

  • 기본키 생성을 데이터베이스에게 위임하는 방식으로 id값을 따로 할당하지 않아도 데이터베이스가 자동으로 AUTO_INCREMENT를 하여 기본키를 생성해준다.
@Entity
public class PkEx() {

  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private Long id;

  private String name;
}


@GeneratedValue(strategy = GenerationType.SEQUNCE)

  • 데이터 베이스의 Sequence Object를 사용하여 데이터베이스가 자동으로 기본키를 생성해준다.
  • @SequenceGenerator 어노테이션이 필요하다.
@Entity
@SequenceGenerator(
	name = "USER_PK_GENERATOR",
	sequenceName = "USER_PK_SEQ",
	initailValue = 1,
  allocationSize = 50
)
public class PkEx() {

  @Id
  @GeneratedValue(strategy = GenerationType.SEQUENCE,
            			generator="USER_PK_GENERATOR")
  private Long id;

  private String name;

}


@GeneratedValue(strategy = GenerationType.TABLE)

  • 키를 생성하는 테이블을 사용하는 방법으로 Sequence와 유사하다.
  • @TableGenerator 어노테이션이 필요하다.
@Entity
@TableGenerator(
  name = "USER_PK_GENERATOR",
  table = "USER_PK_SEQ",
  pkColumnValue = "USER_SEQ",
  allocationSize = 1
)
public class PkEx() {

  @Id
  @GeneratedValue(strategy = GenerationType.SEQUENCE,
            			generator="USER_PK_GENERATOR")
  private Long id;

  private String name;

}


@GeneratedValue(strategy = GenerationType.AUTO)

  • 기본 설정 값으로 각 데이터베이스에 따라 기본키를 자동으로 생성한다.

기본키의 제약 조건

  1. null이면 안된다.
  2. 유일하게 식별할 수 있어야한다.
  3. 변하지 않는 값이어야 한다.


📑 출처

Categories:

Updated:

Leave a comment