Lab 3 Exercise 2 Task 1
Adjusting the table and column names
- Create the com.acme.entities.AuctionUser entitiy
- Follow the same procedure as in Lab 1 Exercise 3 Task 3, steps 1-6
- Add the attributes shown in the Student Guide page 2-9, Figure 2-4
- Press ALT+INSERT to add a default constructor and a constructor accepting all attributes except the auctionUserId
- Add an annotation to save the entity to the table A_USER
- Add an annotation to save the auctionUserId attribute to the id column
- Add an annotation to save the displayName attribute to the name column.
- Set the column length to 50.
- Modify the main method created in Lab 1 to save an AuctionUser entity
- At the beginning of the method create auctionUser JaneDoe with email address jane@doe.com
- After the statement to persist the item, add a similar statement to persist the user
- Choose Run -> Run Main Project
- Follow the same procedure as in Lab 1 Exercise 3 Task 3, step 9 to run the project and verify the table was created as intended and JaneDoe was inserted.
Lab 4 Exercise 2 Task 2
Working with the entity manager
- In the Item entitiy
- Press ALT+INSERT to generate a constructor that takes all attributes except the id as an argument
- Press ALT+INSERT to generate a default constructor
- Create the ItemDao class in the (new) com.acme.daos package
- Add a static EntityManagerFactory attribute
- Initialize the attribute with an EntityManagerFactory for your persistence unit
- Implement the method
private EntityManager getEntityManager()
The method should return an EntityManager created from the EntityManagerFactory attribute
- Implement the method
public Item save(Item item)
- The method should call the getEntityManager method
- The method should persist the item within a transaction
- Look at the main method for inspiration
- return the item
- Create a unit test to test the save() method.
- Right-click the Project node and choose New –> Other.
- Select JUnit from the list of Categories and JUnit Test from the list of File Types, then click Next
- Type ItemTest for the class name
- Select Test Packages as the location
- Type com.acme.daos for the package name
- Click Finish.
- Select JUnit 4.x if prompted for the JUnit version:
- Add an import for static assertXXX JUnit utility methods:
import static org.junit.Assert.*;
- Add a static ItemDao attribute. Initialise it in the @BeforeClass annotated method.
- Create a test method called save() to test the save() method on the ItemDao
- Annotate the method with @Test
- In the test method
- Create a new Item and set all attributes except the id
- Save the Item using the ItemDao
- Use the assertFalse method to test the Item id is not null
assertFalse("id should not be null", item.getId()==null);
- Right click ItemTest.java and choose Run File
If you see a green bar with 100% in it, the test passed. If you see a red bar, the test failed.
- In the ItemDao class, implement the following method:
public Item findByPrimaryKey(Long id)
- Create an annotated test method called find in the ItemTest class to test the findByPrimaryKey method. In this method:
- Create a new Item and set all attributes except the id
- Save the Item using the ItemDao
- Pass the primary key of the saved item to findByPrimaryKey to retrieve the Item from the database
- Use the assertEquals method to test that the key of the returned Item has the same key.
- Run the test and correct errors until it succeeds.
Optional steps
- Create a method in the ItemDao class.
public void deleteByPrimaryKey(Long id)
- Get an entity manager
- Start a transaction
- Look up the Item using the getReference method on the entity manager
- Delete the item using the remove method on the entity manager
- Commit the transaction
- Create an annotated test method called find in the ItemTest class to test the deleteByPrimaryKey method. in this method:
- Create a new Item and set all attributes except the id
- Save the Item using the ItemDao
- Pass the primary key of the saved item to deleteByPrimaryKey to delete the Item from the database
- Pass the primary key of the saved item to findByPrimaryKey to retrieve the Item from the database
- Use the AssertNull method to verify that the item is not found.
Lab 5 Exercise 2 Task 1
Creating a unidirectional One-to-One relationship between two entities
- Create the com.acme.entities.Auction entitiy with these attributes:
private Long auctionId;
private BigDecimal startAmount;
private BigDecimal increment;
private String status;
private Date openTime;
private Date closeTime;
private Item item;
- Map the Date attributes to TIMESTAMP columns using the @Temporal annotation
- Establish a OneToOne relation with Item
- Press ALT+INSERT to generate getters and setters, a default
constructor and a constructor accepting all attributes except the
auctionId
- Create the com.acme.daos.AuctionDao class
- Copy the static EntityManagerFactory attribute from ItemDao
- implement the same methods as in ItemDao, but this time for the Auction entity
- Create a unit test to test the save() method.
- Right-click the Project node and choose New –> Other.
- Select JUnit from the list of Categories and JUnit Test from the list of File Types, then click Next
- Type AuctionTest for the class name
- Select Test Packages as the location
- Type com.acme.daos for the package name
- Click Finish.
- Add an import for static assertXXX JUnit utility methods:
import static org.junit.Assert.*;
- Add an attribute
static AuctionDao auctionDao;
- Initialise it in the @BeforeClass annotated method.
- Create a test method called save() to test the save() method on the ItemDao
- you may modify the method to pass the attributes in the constructor instead of using the setters
@Test
public void save(){
Auction auction = new Auction();
auction.setOpenTime(new Date());
GregorianCalendar cal = new GregorianCalendar();
cal.roll(Calendar.MONTH, true);
auction.setCloseTime(cal.getTime());
auction.setStartAmount(new BigDecimal("100.00"));
auction.setIncrement(new BigDecimal("10.00"));
auction.setStatus(Status.OPEN)
auction = auctionDao.save(auction);
assertTrue("id is greater than zero", auction.getAuctionId() > 0);
}
- Right click ItemTest.java and choose Run File. Run the test and correct errors until it succeeds.
Lab 5 Exercise 3 Task 1
Creating a bidirectional One-to-Many/Many-to-One relationship
- Add a bidirectional One-to-Many/Many-to-One relationship between Auction (1) and Bid (many)
- Add an annotated bids attribute to the Auction entity
- Set cascade mode to ALL
- Initialize the attribute to an empty list of bids
- Add an auction attribute to the Bid entity
- Press ALT+INSERT to generate auction getter/setter methods
- Add an annotation for the relationship
- Press ALT+INSERT to generate a constructor that takes all attributes except the id as arguments
- Press ALT+INSERT to generate a default constructor
- Implement these methods in the Auction entity
public void addBid(Bid bid)
public int getBidCount()
- Implement a saveBids() methods in the AuctionTest class
- Create an auction
- Add 3 new bids with amounts of 150, 175 and 225
- Save the auction
- Assert that the saved auction got an ID
- Assert that the new auction has 3 bids
- Run the test until it passes.
Lab 6 Exercise 2 Task 1
Persisting an Entity with a superclass
- Create an entity called com.acme.entities BookItem.
- Make the BookItem entity a subclass of Item.
- The attributes of the entity are described in module 2 of the Student Guide.
- In the main method add the creation of a BookItem and save it to the database.
- Run the main method
- Examine which changes were made to the database tables
Lab 7 Exercise 2 Task 1
Persisting an Entity with an enum Field
- Create the Status enum.
- Right click on the com.acme.entities package and choose New>Java class
- Type Status for the Class Name.
- Choose enum for the type
- Click OK
- Add these values to the enum: OPEN, CLOSED, CANCELLED
- Refactor the type of Auction.status and change it to Status
- Change getter and setter methods
- Change the call to setStatus in AuctionTest.java
- Run the AuctionTest and correct errors until it succeeds
- Check the database definition of Auction.status and check the inserted data. What has changed?
- Add an Enumerated annotation to the status field and set enumeration type to STRING
- Run the AuctionTest and correct errors until it succeeds
- Check the database definition of Auction.status and check the inserted data. What has changed?
Lab 7 Exercise 3 Task 1
Persisting an Entity with a List field
- Add a Set of String keywords to the Item entity and initialize it to an empty Set.
- Annotate it as an ElementCollection
- Implement these methods:
public void addKeyword(String keyword)
public List<String> getKeywords()
- Add an annotated test method saveKeywords() to ItemTest. You can use the test methods for bids in Auction as a source of inspiration.
- Run the AuctionTest and correct errors until it succeeds.
- Describe the database table where the keywords are saved.
Lab 8 Exercise 2
Performing a query with the Java Persistence API QL
- Add a dynamicJpqlQuery() test to the ItemTest class. In the method
- Perform this JPQL query (within a transaction)
DELETE FROM Item i
- What does this query do?
- Create 3 Items using ItemDao.save(Item i), using different values for all atributes.
- Save them to the database
- Perform a JPQL query to retrieve them
- Assert you retrieved 3 results
- perform a JPQL query to retrieve only items in stock
- Assert you retrieved the correct number of results
- Optional: Add a testPaging() test method that creates 25 Items and retrieves them in groups of maximum 10. Verify that it runs correctly.
Lab 8 Exercise 3
Performing a query with SQL
- Copy the dynamicJpqlQuery() test in the ItemTest class to nativeSqlQuery()
- In the method replace all queries with native queries
Lab 8 Exercise 4
- Add a constructor to the Item class that accepts all attributes
- Type ALT+INSERT into the item class
- Choose Constructor…
- Check all attributes except the ID
- Click Generate
- Add a default constructor to the Item class
- Type ALT+INSERT into the item class
- Choose Constructor…
- Click Generate
- Copy the CriteriaTest.java file from the labs08 directory to the com.acme.entities package in the test directory
- Examine the code
- Run the code
Lab 9 Exercise 2 Task 1
Creating and running a named query
- Define a named query called ClearAuctions using an annotiation on the Auction entity that deletes all auctions
- Define a named query called FindByStatusAuctions using an annotiation on the Auction entity. To define multiple named queries use @NamedQueries:
@NamedQueries( {
@NamedQuery(name="xxx",query="XXXX"),
@NamedQuery(name="yyy",query="YYY") }
- The query should select all auctions with a certain status
- Set the status in the query as a named parameter
- Add an annotated test method called testNamedQuery() to the AuctionTest clas.
- Execute the ClearAuctions query (you can find inspiration in the tests in the previous chapter)
- Do not use the Dao, but create an EntityManager
- Perform the delete operation within a transaction
- Execute the FindByStatusAuctions query to look for all closed auctions
- Assert no entries are found
- Run the test and correct errors until it succeeds
- Modify the testNamedQuery() test to insert three auctions and add them to the auction table
- Add a convenience constructor with common attributes and a default constructor to the entity
- The start date of the first auction should be between those of the second and the third item(we will use this in the next exercise)
- Only two auctions should be in open
- Save them using the Dao
- Assert one entry is found
- Run the test and correct errors until it succeeds
Lab 9 Exercise 2 Task 2
Creating multiple named queries
- Write a new NamedQuery FindAllAuctions that finds all auctions.
- Copy the testNamedQuery() test to a new test and call it testOrderedQuery()
- Replace the last query in the copied test method (FindByStatusAuctions) with the FindAllAuctions Query and store the results in a List
- Assert that the first auction starts after the second.
- Run the test and correct errors until it succeeds
- Write a new NamedQuery called FindAllOrderByOpenTimeAuctions that sorts by ascending openTime.
- Add the query at the end of testOrderedQuery.
- Assert that the first auction starts before the second.
Lab 10 Exercise 2
Performing a Query With Multiple Criteria
- Define a named query called clearItems that deletes all items. Use an annotation on the Item entity
- Add an annotated test method called incompleteItems() to the ItemTest class.
- In the incompleteItems method
- Call the clearItems named query
- Create 3 items.
- An Item with a description
- An Item with an image
- An Item with an image and a description
(Use test methods from previous labs for inspiration)
- Build a criteria query that selects all items that have a description OR an image that is NULL
Hint: use CriteriaBuilder.isNull()
- Execute the query
- Assert 2 entries are found
- Run the test and correct errors until it succeeds
Lab 10 Exercise 3 (extra)
Performing a query with a named parameter
- Copy the incompleteItems() test method and call the copy namedParameter()
- Replace the query with a Criteria query that selects all items with a given description
- The description should be received as a parameter called “desc”
- Execute the query for each description in your items
- Assert that you get exactly one result each time
- Run the test and correct errors until it succeeds
Lab 13 Exercise 2 Task 1
Creating a Composite Key
- Create the BookPk class in the com.acme.enitities package
- Add the @Embeddable annotation and the Serializable interface to theclass declaration.
@Embeddable
public class BookPk implements Serializable{
- Add the following fields:
private String title;
private int edition;
- Right-click an empty line and choose Insert Code.
- Choose Getter and Setter.
- Select all fields and click Generate.
- Right-click an empty line and choose equals() and hashCode().
- Select all fields in the list.
- Click Generate.
- Create the TextBook entity class in the the com.acme.enitities package
- Add an EmbeddedId of type BookPk
- Add attributes
private List<String> authors;
private int yearPublished;
- Extra: Annotate the authors attribute as an ElementCollection
- In the main method add the creation of a BookItem and save it to the database
- Run the main method
- Examine which changes were made to the database tables
Lab 13 Extra: Exercise 3 Task 1
Using validation
- In the projects window right click the libraries folder and select Add Library
- Click Create...
- Enter Library Name: Validation
- Click OK
- Click Add JAR/Folder...
- Select $HOME/pkg/hibernate-validator/hibernate-validator*.jar
- * depends on the version of validator
- Click Add JAR/Folder...
- Select $HOME/pkg/hibernate-validator/lib/required/validator-api-1.0.0.GA.jar
- Click OK
- Click Add Library
- In the Item entity annotate the image with a validation that
- prints the message "Only JPG images are accepted"
- only accept values matching this pattern
".*\\.jpg"
- In the ItemTest class add a test method test Validation that
- saves an Item with a null image
- saves an item with an image string ending in .jpg
- saves an item with an image string ending in .gif
- surround the last save line with a try block
- catch a ConstraintViolationException
- add an empty catch block
- in the try block add as a last line
fail("picture.gif should fail validation");
- Run the test and correct errors until it succeeds
No comments:
Post a Comment