2025년 11월 5일 수요일 (108일차)

Jeonghoon·2025년 11월 5일

jeonghoon's Study

목록 보기
111/128

☕ JPA Entity & 🐦 Dart DIO 정리 문서


🧩 [ JPA (Java Persistence API) ]


🧱 [ Entity ]

어노테이션설명
@Entity해당 클래스를 데이터베이스 테이블과 매핑
@Id해당 테이블의 Primary Key (PK) 지정
@Table(name="테이블명")테이블 이름 지정 (생략 시 클래스명 사용)
@GeneratedValue(strategy = GenerationType.IDENTITY)auto_increment 활성화
@Column(속성명=값)컬럼 속성 정의

🧩 @Column 주요 속성

속성설명
nullabletrue / falsenull 허용 여부
uniquetrue / false중복 허용 여부
name"컬럼명"DB 컬럼명 지정 (생략 시 변수명 사용)
length숫자문자열 컬럼의 길이 제한
insertabletrue / falseinsert 쿼리 포함 여부
updatabletrue / falseupdate 쿼리 포함 여부
columnDefinition문자열직접 SQL 타입 정의 (예: TEXT, VARCHAR 등)

💡 Tip: insertable=false, updatable=false 설정은 자동 갱신 방지에 유용하다.


🕒 [ JPA Auditing ]

  • Entity의 생성 및 수정 시간을 자동으로 기록하는 기능
  • SQL의 INSERT / UPDATE 시점을 감지하여 createDate, updateDate 필드 자동 주입

⚙️ 사용법

  1. 메인 클래스(AppStart) 위에 @EnableJpaAuditing 주입
  2. BaseTime 클래스 정의
@Getter
@MappedSuperclass                              // Entity 상속용으로 사용
@EntityListeners(AuditingEntityListener.class) // Auditing 활성화
public class BaseTime {
    @CreatedDate                        // 현재 날짜 및 시간 자동 주입
    private LocalDateTime createDate;   // 생성일
    @LastModifiedDate                   // 수정 날짜 자동 주입
    private LocalDateTime updateDate;   // 수정일
}
  1. Entity 클래스에서 BaseTime을 상속
@Entity
public class UserEntity extends BaseTime {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String username;
}

📘 결과: INSERT 시 createDate, UPDATE 시 updateDate 자동 반영.


🐦 [ Dart & Flutter ]


🌐 [ 주요 통신 기술 비교 ]

언어 / 프레임워크주요 통신 기술
JavaScriptfetch()
JQuery$.ajax()
Reactaxios
FlutterDIO

🧩 [ Flutter 주요 라이브러리 ]

환경관리 파일 / 설치 방식
Springbuild.gradle
JavaScriptCDN
Reactnpm (Node Package Manager)
Flutterpubspec.yaml

📦 공식 패키지 공유 사이트: https://pub.dev/


⚙️ [ DIO (HTTP Client for Flutter) ]

  • Flutter에서 API 통신을 위한 대표 HTTP 클라이언트 패키지

📘 설치 방법

  1. pubspec.yaml 파일의 dependencies: 아래에 추가
dependencies:
  dio: ^5.9.0
  1. Pub get 클릭하여 설치
  2. Dart 파일에서 Dio 객체 생성
import 'package:dio/dio.dart';

final dio = Dio();

⚠️ 주의사항:
Flutter 앱 환경은 localhost 접근 불가능, 실제 IP 주소 또는 도메인 사용 필요.


💻 [ DIO 기본 사용 예시 ]

import 'package:dio/dio.dart';

void main() async {
  final dio = Dio();

  try {
    final response = await dio.get('https://jsonplaceholder.typicode.com/posts/1');
    print(response.data);
  } catch (e) {
    print("요청 실패: $e");
  }
}

💡 awaitasync를 함께 사용하여 비동기 통신을 처리한다.


⚡ [ Flutter 주요 문법 ]

문법설명
initState()위젯이 최초 실행될 때 1회 실행, React의 useEffect(()=>{}, [])와 유사
setState((){})변수의 상태 변경 및 화면 리렌더링
dispose()위젯이 사라질 때 실행 (리소스 정리용)

📘 예시 코드

class MyApp extends StatefulWidget {
  
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  String message = "Hello Flutter";

  
  void initState() {
    super.initState();
    print("initState 실행됨!");
  }

  void changeText() {
    setState(() {
      message = "상태가 변경되었습니다!";
    });
  }

  
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text("DIO Example")),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text(message),
            ElevatedButton(onPressed: changeText, child: Text("Change Text"))
          ],
        ),
      ),
    );
  }
}

0개의 댓글