0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

SpringBoot データベーステーブルの列名(カラム名)がスネークケースだった場合の対処

Posted at

前提(テーブルの列名がスネークケース)

SpringDataJPAを使用
エンティティにf_testというテーブルを設定

Entitiytest.java
package com.example.demo.entity;

import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.Table;

@Entity
@Table(name = "f_test" , schema = "main")
public class Entitiytest {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long kojin_no;

    //getter, setter
}

リポジトリに指定のkojin_noを抽出するよう記述

RepositoryTest.java
package com.example.demo.repositry;

import java.util.List;

import org.springframework.data.jpa.repository.JpaRepository;
import com.example.demo.entity.EntityTest;

public interface RepositoryTest extends JpaRepository<EntityTest, Long> {
	List<EntityTest> findByKojinNo(String kojin_no);
}

findByKojinNoの「findBy」は固定値で、
KojinNoは抽出したい列名と同じスペルで記述する必要があるが、
スネークケースの場合は、キャメルケースに変換する必要がある。
そして、列名の先頭は大文字で始める必要あり。

ゆえに、kojin_no → KojinNo → findByKojinNo

ここまでは問題ないはずだが、
実行させるとkojinNoなんて列は指定のテーブルにないと怒られる

どうしたらいいか

いきなり答え

Entitiytest.java
package com.example.demo.entity;

import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.Table;

@Entity
@Table(name = "f_test" , schema = "main")
public class Entitiytest {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    //private Long kojin_no;
    @Column(name = "kojin_no")   //←こうする
    private Long kojinNo;        //←こうする

    //getter, setter
}

エンティティ側もキャメルケースにする必要がある
ただし、それだけだと実際にテーブルを見に行く際も「kojinNo」として見に行くため、
それを回避するために実際の列名は「kojin_no」だよという
@Column(name = "kojin_no")が必要ということらしい

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?