① Add a tag to pom.xml.
<!-Settings to enable DataJpa in Spring Boot->
② Create an Entity class.
Add [must] @Entity. This indicates that it is an Entity class. Add [must] @Table.name is the name of the DB table. If omitted, it will be mapped to a table with a capitalized class name. [must] Add @Id to the column with PRIMARY KEY. It will not work without @Id. If not, add PRIMARY KEY to DB or Add @GeneratedValue (strategy = GenerationType.IDENTITY). With this, you can generate a PRIMARY KEY. If DB is a composite key, use @ javax.persistence.EmbeddedId
Add [must] @Column and specify the column name to be mapped. If omitted, the property name will be mapped to the column with the capitalized name.
import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table;
// Entity class = DB table @Entity @Table(name = "player") public class Player {
@Id
@Column(name = "id")
private Integer id;
@Column(name = "name")
private String name;
@Column(name = "nationality")
private String nationality;
// Getter Setter below
③ Create a repository. Make it with an interface instead of the usual class.
[must] Add the following after the class name.
⬇ ︎
extends JpaRepository<Player, Integer>
import org.springframework.data.jpa.repository.JpaRepository; import jp.co.rakus.football.entity.Player;
//JpaRepositoryを継承する事で、fineOne、findAll、save、deleteの4メソッドが使用 // Generics specifies the entity's class name and primary key type. public interface PlayerRepository_DataJpa extends JpaRepository<Player, Integer> {
}
④ Now that it is ready, use it in services and controllers.
@Service @EnableTransactionManagement public class PlayerService {
@Autowired
PlayerRepository_DataJpa playerRepository_DataJpa;
public List<Player> findAll() {
return playerRepository_DataJpa.findAll();
}
public void saveUserInfo(User user) {
userRepositoryDataJpa.save(user);
}
}
Recommended Posts