Lab 1 Exercise 0
Adding Hibernate JPA 2 support (NetBeans < 7.2)
- Start the NetBeans IDE
- Select Tools > Libraries
- New Library...
- Library Name: HibernateJPA2
- Add Jar/Folder...
- Go to the $HOME/pkg directory and add jars as described here
- Click OK
- Select this library in subsequent exercises when you need to add a JPA 2 library
Lab 1 Exercise 2 Task 1: alternate instructions
Running the java DB Database
- If required start the Java DB database server
- Select Window > Services to open the Services pane.
- Open the Services tab and expand Databases.
- Right-click JavaDB and select Start Server.
- If you get a permission error, look here.
- Create an Employee database in NetBeans.
- Right-click JavaDB and select Create Database.
- Enter auction the database name.
- Enter student as the username.
- Enter student as the password. (Enter the password twice.)
- Click OK
- Right click the created database and click Connect
Lab 1 Exercise 2 Task 3: Hibernate instructions
Creating a Simple Entity
- Put the JDK level of your project to JDK 6 (the Hibernate 3.6 Modelgen module does not support JDK 7)
- Right click project => Properties
- Set Source/Binary format to JDK 6
- Create the Item entity class
- Right click JPA-03 in the Projects tab and choose New => Other => Persistence => Entity Class
- Type Item for the Class Name
- Type com.acme.entities for the package
- Click Next
- Make sure the persistence Unit Name is JPA-03PU
- Select Hibernate (JPA2) as the Persistence Library
- Choose the following for Database Connection:
jdbc:derby://localhost:1527/auction [user on USER] - Select Create for the Table Generation Strategy.
- Click Finish.
- View the persistence.xmlfile.
- Expand JPA-03 -> Source Packages -> META-INF.
- Double-click persistence.xml.
- After you have explored the Design view, click the Source button to
explore the XML. - Modify the Item entity
- Rename the primary key field to itemId.
- Position the cursor on the id field and click CTRL-R
- Type itemId in the New Name field
- Select Rename Getters and Setters
- Click Refactor.
- Add the description, image, and inStock fields
- Press ALT+INSERT in the Item class and select Add Property...
- Set the name to description and click OK
- Add another property image
- Add another property inStock of Type Boolean
- Add constructors to the Item entity
- Press ALT+INSERT in the Item class and select Generate Constructor...
- Click Generate
- Generate another constructor with all fields to be initialised, except the itemId.
- Save the Item entity to the database
- Double click the jpa03.Main class
- Press ALT+INSERT in the class and select Use Entity Manager...
- Make the persist method static
- From the main method call the persist method and pass a new Item to it with these attributes
- description: mouse pad
- image: mousepad.jpg
- inStock: true
- Add the Java DB client driver to the project
- Right-click Libraries under JPA-03 and choose AddJAR/Folder.
- Navigate to $GLASSFISH_HOME\javadb\lib and select derbyclient.jar
- Click OK
- Choose Run -> Run Main Project
- Verify that the ITEM table has the new INSTOCK field.
a. Select the Services tab of the IDE.
b. Expand the following JDBC Connection node:
jdbc:derby://localhost:1527/auction [student on STUDENT]
c. Expand the STUDENT -> Tables node.
d. Right-click ITEM and choose Refresh. - Verify that the Item entity was saved to the database.
a. Right-click the ITEM table and choose View Data
Lab 3 Exercise 2 Task 1: high level instructions
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
- Move the EntityManagerFactory local variable (and instantiation) to a private static attribute
- 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 1: Hibernate instructions
Customising the Persistence Unit
- Open META-INF/persistence.xml. Make sure that the view is set to Source.
- Add a <description> subelement to the <persistence-unit> element
- Add a new line below the <persistence-unit ... > tag.
- Type < and press CTRL+SPACE
- Choose description
- Complete the element by choosing </description>
- Add a body to the description element
Hibernate/JavaDB PU - Choose Run -> Run Main Project and correct any errors until the project runs well
- Select the <class> element that holds the Bid entity. From the menu bar use Source => Toggle comment, to comment out the element
- Add an XML element to exclude-unlisted-classes after the last class element.
- In the project view, right click the project and choose Clean and Build
- Choose Run -> Run Main Project. You should see an exception saying Bid is not recognised as an entity.
- Uncomment the Bid element
- Change the password in the persistence.xml file to force an authentication failure.
- Choose Run -> Run Main Project. You should see an exception signaling an authentication problem.
- Set the pasword back to its original value and set exclude-unlisted-classes to false
- Choose Run -> Run Main Project and correct any errors until the project runs well
Lab 4 Exercise 2 Task 2: High level instructions
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
- Add a static EntityManagerFactory attribute
- 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
- 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.
assertFalse("id should not be null", item.getId()==null);
- 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.
- 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: High level instructions
-
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
- Implement similar 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 the com.acme.entities.Auction entitiy with these attributes:
- 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
- Right click ItemTest.java and choose Run File. Run the test and correct errors until it succeeds.
@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); }
Lab 5 Exercise 3 Task 1: High level instructions
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()
- Add an annotated bids attribute to the Auction entity
- 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: High level instructions
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: High level instructions
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
- Right click on the com.acme.entities package and choose New>Java class
- 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: High level instructions
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 Collection<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: High level instructions
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)
- 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.
DELETE FROM Item i
Lab 8 Exercise 3: High level instructions
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: High level instructions
- Copy the CriteriaTest.java file from the labs08 directory in the solutions 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
- Build a criteria query that selects all items that have a description OR an image that is NULL
Hint: use static methods in Restrictions - Execute the query
- Assert 2 entries are found
- Run the test and correct errors until it succeeds
Lab Design Patterns Exercise 1
In this lab you will build a superclass with common behaviour for Data Access Objects.To keep things simple, this template supposes that all primary keys are of type Long.
- Copy the GenericJpaDao template from $HOME/labs/lab_design to the com.acme.daos package.
- Implement the empty methods (look for //TODO comments)
- Use the TClass attribute whenever you need to supply the entity class
- Adapt the class that interacts with the database for Item entities to use GenericJpaDao
- Let the class inherit from GenericJpaDao
public class ItemDao extends GenericJpaDao<Item>
- Refactor all methods in the ItemDao so there names match the names used in GenericJpaDao (Refactoring will update all classes that use these methods to use the new names)
- Then delete these methods
- In the Item Test class
- Create attributes
private static EntityManagerFactory emf; private static ItemDao itemDao;
- If not yet present, create a method
- In the method
- create a factory with the name of your persistence unit
- call itemDao.setEntityManagerFactory(emf);
- Create a static attribute for the ItemDao and assign an instance to it in SetUpClass()
- Review your test methods and use the created Data Access Object in them
- Run the tests until they succeed
- Write down some suggestions for enhancing the GenericJpaDao class
@BeforeClass public static void setUpClass(){}
Lab Performance Exercise 1
Using data filters
- Define a filter called BidsApproved that limits bids to those that have their approval set to "OK"
- Annotate the Bid class to associate the filter BidsApproved with it.
- Write a test method called testApprovedBids(). In the testmethod
- Initialize test data
- Clear all the Bids from the database
- Clear all the Auctions from the database
- Create an Auction
- Create 3 bids
- Only one bid should have approved set to "OK"
- All bids should be associated with the Auction
- Add all bids to the Auction (bidirectional relation)
- Save the Auction
- Enable the BidsApproved filter
- Select all the bids
- Assert that only one bid is returned
- Disable the BidsApproved filter
- Run the test and correct errors until it succeeds
- Extend the test method (just before disabling the bidsApproved filter
- Select all the Auctions
- Get all the Bids from the first Auction that is returned
- Assert that only one bid is returned
- disable the BidsApprovedfilter at the end of te
- Run the test and write down the result
- Activate the filter on the bids Collection
- In the Auction class, annotate the bids attribute with the BidsApproved filter
- Run the test and correct errors until it succeeds
Lab Performance Exercise 2
Adding L2 EhCache support
- In the projects tab, right click the Libraries folder and choose "Add Jar/Folder..."
- Go to the $HOME/pkgpkg/ehcache/lib directory and add the ehcache-core jar
- Add caching support to persistence.xml
- Set the hibernate.cache.use_second_level_cache property to true
- Add the EhCache provider
- For monitoring
- set the hibernate.generate_statistics property to true
- Make sure you log Hibernate generated SQL
<property name="hibernate.cache.region.factory_class" value="org.hibernate.cache.SingletonEhCacheRegionFactory"/>
Caching the Item entity
- Add READ_ONLY caching to the Item entity using the @Cache annotation (from org.hibernate.annotations)
- Add an annotated test method called testReadCache() to the ItemTest class. Throughout this exercise, print out what you are doing before each database access, to make your test output easier to follow. In the test method do these actions:
- Create a org.hibernate.stat.Statistics objec
- Get a hibernate SessionFactory from the EntityManagerFactory
- Get the Statistics object from the SessionFactory
- Create an Item, save it and get its ID
- Print out cache hits and misses
- Lookup the Item again, using the ID
- Print out cache hits and misses
- Lookup the Item again, using the ID
- Print out cache hits and misses
- Run the tests and correct any errors. Observe the cache behaviour. Observe that the generated SQL statements are not printed when the cache is used.
- At the end of the test method add code to:
- Evict everything from the cache
- Lookup the Item
- Print out cache hits and misses
- Run the tests and correct any errors. Observe the cache behaviour.
- At the end of the test method add code to:
- Modfy the description of the Item to "changed"
- Merge the saved Item to the database
- Add an update(Item it) method to the ItemDao class for this (if it did not exist yet).
- Lookup the Item
- Print out cache hits and misses
- Assert that the description of the looked up Item is set to "changed"
- Run the test. Record the cache behaviour. An exception can be thrown.
- Modify the Item caching concurrency annotation to NONSTRICT_READ_WRITE
- Run the test until it succeeds. Record the cache behaviour and compare with the previous result.
- Modify the Item caching concurrency annotation to READ_WRITE
- Run the test until it succeeds. Record the cache behaviour and compare with the previous result.
Caching the keywords collection
- In the testReadCache() method, add some keywords to the Item, before it is initially saved to the database.
- At the end of the method, add these instructions (remember to add some tracing statements as well):
- get the number of keywords associated with the Item
- Print out cache hits and misses
- Lookup the Item again, using the ID
- Print out cache hits and misses
- get the number of keywords associated with the Item
- Print out cache hits and misses
- Run the test. Record the cache behaviour.
- Annotate the keywords collection to cache it with READ_WRITE concurrency
- Run the test until it succeeds. Record the cache behaviour and compare with the previous result.
No comments:
Post a Comment