Skip to content

Instantly share code, notes, and snippets.

@gatanity
Created May 18, 2020 14:55
Show Gist options
  • Save gatanity/b36d4fed88f6887d1d8523384d5bb4e1 to your computer and use it in GitHub Desktop.
Save gatanity/b36d4fed88f6887d1d8523384d5bb4e1 to your computer and use it in GitHub Desktop.
Retrieving an entity without a default constructor
package net.millenary.gtdev.exmaples.domain.edward;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class Edward {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private final Integer age;
public Edward(Integer age) {
this.age = age;
}
public Integer getAge() {
return age;
}
}
package net.millenary.gtdev.exmaples.domain.edward;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface EdwardRepository extends JpaRepository<Edward, Long> {}
package net.millenary.gtdev.exmaples.domain.edward;
import javax.annotation.PostConstruct;
import javax.persistence.EntityNotFoundException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class EdwardTester {
private final EdwardRepository repository;
@Autowired
public EdwardTester(EdwardRepository repository) {
this.repository = repository;
}
@PostConstruct
private void showAgeOfEdward() {
/* 20歳のエドワードを永続化 */
Edward edward = new Edward(20);
this.repository.saveAndFlush(edward);
/* ID 1 のエドワードを取得 */
edward = this.repository.findById(1L).orElseThrow(() -> new EntityNotFoundException("Edward has gone"));
System.out.println(edward.getAge());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment