When we create the Entity and respority, we also need to does validations to protect our data.
In Java, validations is built-in, using decorators. For Typescript, found a useful libaray to does the similar validation as well. Checkout Class-validator
Entity:
@Entity Public classBook {// ====================================== //= Attributes =// ======================================@Id @GeneratedValuePrivateLong ID; @Column (Length= 200) @NotNull @Size (min = 1, max = $)PrivateString title; @Column (Length= 10000) @Size (min = 1, max = 10000)PrivateString Description; @Column (Name= "Unit_cost") @Min ( 1)PrivateFloat unitcost; @Column (Length= 50) @NotNull @Size (min = 1, max = +)PrivateString ISBN; @Column (Name= "Publication_date") @Temporal (temporaltype.date) @Past PrivateDate publicationdate; .... }
Testing:
We want to test, if we give title as null, it should throw exception.
@RunWith (Arquillian.class) Public classbookrepositorytest {@InjectPrivatebookrepository bookrepository; //We want the test throw exception @Test (expected = exception.class) Public voidCreateinvalidbook () { Book Book=NewBook ("ISBN",NULL, 12F, 123, Language.english,NewDate (), "ImageURL", "description"); Bookrepository.create (book); } @Deployment Public Staticjavaarchive createdeployment () {returnShrinkwrap.create (javaarchive.class). addclass (bookrepository.class). addclass (book.class). addclass (Language.class). Addasmanifestresource (Emptyasset.instance,"Beans.xml"). Addasmanifestresource ("Meta-inf/test-persistence.xml", "Persistence.xml"); } @org. junit.test Public voidCreate () {}}
Respority:
@Transactional (SUPPORTS) Public classBookrepository {// ====================================== //= Injection Points =// ======================================@PersistenceContext (Unitname= "Bookstorepu") PrivateEntitymanager em; // ====================================== //= Business methods =// ====================================== PublicBook find (@NotNull Long id) {returnEm.find (book.class, id); } //for creating and deleting methods, we want to use REQUIRED@Transactional (REQUIRED) PublicBook Create (@NotNull book book) {em.persist (book); returnBook ; }}
Testing:
@Test (expected = exception.class) publicvoid Findwithinvalidid () { bookrepository.find (null); }
[Java EE] Data Validation