In this exercise, you will practice different strategies of inheritance using Spring JPA in the context of a Dungeons and Dragons game. You will work with entities representing characters and items in the game.
-
Set up a new Spring Boot project with the necessary dependencies for Spring JPA and a database of your choice (e.g., H2, MySQL).
-
Create the following entity classes:
Character
(abstract base class)id
(Long)name
(String)level
(int)attack()
(abstract method)
Player
(extendsCharacter
)characterClass
(String)race
(String)- Implement the
attack()
method specific to players
Monster
(extendsCharacter
)monsterType
(String)hitPoints
(int)- Implement the
attack()
method specific to monsters
Item
(abstract base class)id
(Long)name
(String)use()
(abstract method)
Weapon
(extendsItem
)damage
(int)weaponType
(String)- Implement the
use()
method specific to weapons
Armor
(extendsItem
)defense
(int)armorType
(String)- Implement the
use()
method specific to armor
-
Implement the following inheritance strategies:
- Use the joined table strategy for the
Character
entity hierarchy (Player
andMonster
). - Use the single table strategy for the
Item
entity hierarchy (Weapon
andArmor
).
- Use the joined table strategy for the
-
Create repository interfaces for each entity using Spring Data JPA.
-
Create a
CharacterService
class with the following methods:createPlayer(String name, String characterClass, String race, int level)
: Creates and save a new player character.createMonster(String name, String monsterType, int hitPoints, int level)
: Creates and save new monster character.equipWeapon(Long characterId, Long weaponId)
: Equips a weapon to a character. This method should only log a message saying "Weapon equipped" without modifying the database.equipArmor(Long characterId, Long armorId)
: Equips armor to a character. This method should only log a message saying "Armor equipped" without modifying the database.attackWithCharacter(Long characterId)
: Invokes theattack()
method of a character.
The
CharacterService
class should use the repository interfaces to persist and retrieve data from the database. -
Create a
DataLoader
class that implements theCommandLineRunner
interface. In therun()
method, use theCharacterService
to perform the following actions:- Create a few player characters and monster characters.
- Create a few weapons and armor pieces.
- Equip weapons and armor to characters. This should only result in logging messages.
- Invoke the
attack()
method of characters.
- Implement a
SpecialAbility
abstract class with aperform()
method, and create subclassesMagicSpell
andPhysicalAbility
that extendSpecialAbility
. Use the table-per-class strategy for this hierarchy. - Extend the
CharacterService
to include methods for assigning special abilities to characters and invoking theirperform()
methods.
Embark on this coding adventure and may your inheritance strategies be victorious!