Ir ao conteúdo
  • Cadastre-se

Java JPA está criando colunas a partir de métodos getters


Posts recomendados

Olá!

Estou tentando criar uma tabela no banco de dados com uso das anotações jpa, mas não está funcionando quando coloco elas nos atributos, apenas nos métodos. Existem métodos que não acessam os atributos da classe, mas retornam um dado de um serviço e o jpa está criando essa coluna no banco de dados.

 

package br.firmacore.controllers.house.DAO.models;

import br.firmacore.Main;
import br.firmacore.controllers.house.exceptions.HouseMembersLimitException;
import br.firmacore.controllers.house.exceptions.HouseSizeLimitException;
import br.firmacore.controllers.house.exceptions.HouseWorldException;
import br.firmacore.enums.AreaTypeEnum;
import br.firmacore.enums.PermissionsEnum;
import br.firmacore.hooks.VaultHook;
import br.firmacore.hooks.exceptions.PlayerHasNoMoneyException;
import br.firmacore.services.WEService;
import br.firmacore.services.WGService;
import br.firmacore.services.exceptions.*;
import br.firmacore.utils.MessageUtils;
import br.firmacore.utils.SpigotUtils;
import com.sk89q.worldguard.protection.flags.Flags;
import com.sk89q.worldguard.protection.flags.RegionGroup;
import com.sk89q.worldguard.protection.flags.StateFlag;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.entity.Player;

import javax.persistence.*;
import java.util.*;

@Table(name = "house")
public class House {
    @Transient public static final long BLOCK_VALUE = 1000;
    @Transient public static final long PVP_VALUE = 10000;
    @Transient public static final int MAX_TAXES = 6;
    @Transient public static final AreaTypeEnum AREA_TYPE = AreaTypeEnum.CASA;
    @Transient private List<Tribute> tributes = new ArrayList<>();
    @Transient private ProtectedRegion region;
    @Transient private Player player;

    @Id private String uuid;
    @Column(name = "world") private String world;
    @Column(name = "x") private double x;
    @Column(name = "y") private double y;
    @Column(name = "z") private double z;
    @Column(name = "size") private int size;
    @Column(name = "dayBuy") private int dayBuy;
    @Column(name = "hourBuy") private int hourBuy;

    public House(Player owner, int size) throws ProtectionAlreadyExistsException, HouseWorldException, HouseSizeLimitException, PlayerHasNoMoneyException {
        if(!worldIsCorrect(owner)) throw new HouseWorldException();
        if(sizeInLimit(owner, size)) throw new HouseSizeLimitException();
        if(!playerHasMoney(owner, size)) throw new PlayerHasNoMoneyException();
        this.uuid = owner.getUniqueId().toString();
        this.world = owner.getWorld().getName();
        this.x = owner.getLocation().getX();
        this.y = owner.getLocation().getY();
        this.z = owner.getLocation().getZ();
        this.player = owner;
        this.size = size;
        this.dayBuy = Calendar.getInstance().get(Calendar.DAY_OF_WEEK);
        this.hourBuy = Calendar.getInstance().get(Calendar.HOUR_OF_DAY);
        createHouse(size);
    }


    // [#] Funcionalidades
    public void infoHouse(){
        MessageUtils.messageToPlayer(this.player, "");
        MessageUtils.messageToPlayerWithTag(this.player, "&6Informações da Casa");
        MessageUtils.messageToPlayer(this.player, "");
        MessageUtils.messageToPlayer(this.player, "   &6● &7Proprietário: &3" + this.player.getName().toUpperCase());
        MessageUtils.messageToPlayer(this.player, "   &6● &7Tamanho: &8" + this.size);
        MessageUtils.messageToPlayer(
                this.player,
                "   &6● &7Tributos: &8" + this.tributes.size() +
                         " &7(&c-" + VaultHook.getEconomy().format(calculateTotalTributesValue()) + "&7)"
        );
        MessageUtils.messageToPlayer(this.player, "");
    }

    public void removeProtection() throws ProtectionNotFoundException {
        WGService.removeProtection(this.player.getName(), AreaTypeEnum.CASA);
    }

    public void addFriend(String target) throws ProtectionNotFoundException, HouseMembersLimitException, MemberAlreadyExistsException {
        if(membersInLimit()) throw new HouseMembersLimitException();
        WGService.addMember(this.player.getName(), target, AREA_TYPE);
    }

    public void deleteFriend(String target) throws MemberNotExistsException, ProtectionNotFoundException {
        WGService.removeMember(this.player.getName(), target, AREA_TYPE);
    }

    public void updateHome(Location location) throws PlayerIsntInRegion, ProtectionNotFoundException {
        if(WGService.playerIsInRegion(location, this.player.getName(), AREA_TYPE)){
            this.x = location.getX();
            this.y = location.getY();
            this.z = location.getZ();
        }
    }

    public void updatePVP(){
        region.setFlag(
                Flags.GREET_MESSAGE,
                setGreetMessage(isPvp())
        );
        region.setFlag(Flags.PVP, isPvp() ? StateFlag.State.DENY : StateFlag.State.ALLOW);
    }

    public void expandSize(int size) throws HouseSizeLimitException, ProtectionNotFoundException {
        if(sizeInLimit(this.player,this.size + size)) throw new HouseSizeLimitException();

        this.region = WGService.expandProtection(
                this.player.getName(),
                AREA_TYPE,
                region.getMaximumPoint().getX(),
                region.getMaximumPoint().getZ(),
                region.getMinimumPoint().getX(),
                region.getMinimumPoint().getZ(),
                size
        );
        this.defineHouseFlags(isPvp());
        this.region.getOwners().addPlayer(this.player.getName());
        this.region.setPriority(100);
        this.size += size;

        this.removeProtection();
        WGService.getRegionManager().addRegion(this.region);
        WEService.createBorder(
                region.getMaximumPoint().getX(),
                region.getMinimumPoint().getX(),
                region.getMaximumPoint().getZ(),
                region.getMinimumPoint().getZ(),
                this.player.getWorld()
        );
    }

    public void teleport(Main plugin, Player player){
        SpigotUtils.teleportPlayer(
                plugin,
                player,
                new Location(Bukkit.getWorld(this.world), this.x, this.y, this.z)
        );
    }


    // [#] House Configurations
    private String setGreetMessage(boolean pvp){
        String pvpTAG = pvp ? " &7[&a&lPVP OFF&7] " : " &7[&c&lPVP ON&7] ";
        return pvpTAG + "&8&l>> &6Olá, bem-vindo(a) à &8" + AREA_TYPE + " &6de &8" +
                this.player.getName() + "&6!";
    }

    private void createHouse(int size) throws ProtectionAlreadyExistsException {
        ProtectedRegion region = WGService.createProtection(
                this.player.getName(),
                AREA_TYPE,
                this.player.getLocation().getBlockX(),
                this.player.getLocation().getBlockZ(),
                size
        );
        this.defineHouseFlags(false);
        region.getOwners().addPlayer(this.player.getName());
        region.setPriority(100);

        WGService.getRegionManager().addRegion(region);
        WEService.createBorder(
                region.getMaximumPoint().getX(),
                region.getMinimumPoint().getX(),
                region.getMaximumPoint().getZ(),
                region.getMinimumPoint().getZ(),
                this.player.getWorld()
        );
    }

    private void defineHouseFlags(boolean pvp) {
        region.setFlag(Flags.GREET_MESSAGE, setGreetMessage(pvp));
        updatePVP();
        region.setFlag(Flags.OTHER_EXPLOSION, StateFlag.State.DENY);
        region.setFlag(Flags.ENDER_BUILD, StateFlag.State.DENY);
        region.setFlag(Flags.BLOCK_BREAK.getRegionGroupFlag(), RegionGroup.MEMBERS);
        region.setFlag(Flags.BLOCK_PLACE.getRegionGroupFlag(), RegionGroup.MEMBERS);
    }


    // [#] Regras de Negócio
    private boolean playerHasMoney(Player owner, int size){
        return (VaultHook.getEconomy().getBalance(owner) >= calculateHouseValue(size));
    }

    private boolean sizeInLimit(Player owner, int size){
        return ((size < 10) || (size > 50 && !owner.hasPermission(PermissionsEnum.VIP.getPermission())));
    }

    private boolean worldIsCorrect(Player owner){
        World world = owner.getWorld();
        return !world.getEnvironment().equals(World.Environment.NETHER) ||
                world.getEnvironment().equals(World.Environment.THE_END);
    }

    private boolean membersInLimit() throws ProtectionNotFoundException {
        int amountMembers = WGService.getAmountMembers(this.player.getName(), AREA_TYPE);
        return (
                amountMembers == 3 ||
                        (this.player.hasPermission(PermissionsEnum.VIP.getPermission()) &&
                                amountMembers == 6
                        )
        );
    }


    // [#] Matematica
    public static double calculateHouseValue(int size){
        return (BLOCK_VALUE * size);
    }

    public double calculateTotalTributesValue(){
        return this.tributes.stream().mapToDouble(Tribute::getValue).sum();
    }


    // [#] Tributos
    public void addTribute(Tribute tribute){
        this.tributes.add(tribute);
    }
    
    public double payTributes() throws PlayerHasNoMoneyException {
        double total = calculateTotalTributesValue();
        if(VaultHook.getEconomy().getBalance(this.player) >= total){
            VaultHook.getEconomy().withdrawPlayer(this.player, total);
            this.tributes.clear();
            return total;
        }
        throw new PlayerHasNoMoneyException();
    }


    // [#] Getters and Setters
    @Transient public boolean isPvp() {
        return region.getFlag(Flags.PVP) == StateFlag.State.ALLOW;
    }

    @Transient public Set<String> getMembers() throws ProtectionNotFoundException, MembersEmptyException {
        return WGService.getMembers(this.player.getName(), AREA_TYPE);
    }

    @Transient public List<Tribute> getTributes() {
        return tributes;
    }

    @Transient public Player getOwner() {
        return player;
    }

    public String getUuid() {
        return uuid;
    }

    public String getWorld() {
        return world;
    }

    public double getX() {
        return x;
    }

    public double getY() {
        return y;
    }

    public double getZ() {
        return z;
    }

    public int getSize() {
        return size;
    }

    public int getDayBuy() {
        return dayBuy;
    }

    public int getHourBuy() {
        return hourBuy;
    }
}

 

foi necessário eu adicionar

@ Transient

nesse métodos que nem sequer tem atributo. Foi preciso também criar métodos getters para todos os atributos que eu desejo persistir, sendo que algum deles eu nem uso. Se eu definir "

@ Column(name = “world”) private String world;

" e não adicionar um método getter, a coluna não é criada no banco de dados. "

@ Id private String uuid;

" está gerando por causa do getter, mas não como chave primária, talvez eu tenha que adicionar

@ Id

no método getter do uuid para funcionar. Alguém sabe a solução?

Link para o comentário
Compartilhar em outros sites

Crie uma conta ou entre para comentar

Você precisa ser um usuário para fazer um comentário

Criar uma conta

Crie uma nova conta em nossa comunidade. É fácil!

Crie uma nova conta

Entrar

Já tem uma conta? Faça o login.

Entrar agora

Sobre o Clube do Hardware

No ar desde 1996, o Clube do Hardware é uma das maiores, mais antigas e mais respeitadas comunidades sobre tecnologia do Brasil. Leia mais

Direitos autorais

Não permitimos a cópia ou reprodução do conteúdo do nosso site, fórum, newsletters e redes sociais, mesmo citando-se a fonte. Leia mais

×
×
  • Criar novo...