How to enable hibernate / suspend to disk in GNOME?

I have an Arch Linux laptop with GNOME installed. I expected that Power Off / Log Out menu should contain a hibernate item, but it does not. Note: I have a swap file working.

enter image description here

sleep – Why does my Windows 10 laptop fail to hibernate, if I don’t Sleepen it just beforehand?

Too often, when I press “Hibernate”, my Windows 10 laptop fails to Hibernate. The screen goes black, but even after 20 minutes, the hardware is still running.

Then I shake my mouse and the screen shows up again. Now if I press “Sleep”, my laptop sleeps. When I waken it, then press “Hibernate”, finally the laptop Hibernates. Why? How does Sleepening my laptop make it Hibernate? Why didn’t it hibernate on its own the first time?

java – Select Dinamico (Spring MVC JPA HIBERNATE)

Cómo puedo obtener en un <form:select> de registrar_libro.jsp, todos los nombres de la tabla imagenes, yo quiero todos los registros de la tabla imagenes, no solo el relacionado.

Estas tablas (libro e imagenes) tienen una relación 1:1.

Clase Libro

@Entity
@Table(name = "libros")
public class Libro implements Serializable {
     @OneToOne
     @JoinColumn(name = "imagenId", nullable = false, unique = true,
        foreignKey = @ForeignKey(foreignKeyDefinition = "foreign key(imagenId) references imagen(id)"))
     private Imagen imagen;
}

Clase Imagen

@Entity
@Table(name = "imagen")
public class Imagen implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;
    private String nombre;

    @Column(columnDefinition = "longblob")
    private byte() file;
    @OneToOne(mappedBy = "imagen")
    private Libro libro;
}

registrar_libro.jsp

<form:form name="" method="post" modelAttribute="libro">
        Titulo: <form:input type="text" path="titulo"/> <br>
        Autor: <form:input type="text" path="autor"/> <br>
        Editorial: <form:input type="text" path="editorial"/> <br>
        Edicion: <form:input type="number" path="edicion" step="any"/> <br>
        <form:label path = "imagenes">Country</form:label>
        
        <!------- AQUI ------------->
        <form:select path = "imagenes">
            <form:option value = "NONE" label = "Select"/>
            <form:options items = "${listaImagenes}" />
        </form:select>

        <button type="submit">Guardar</button>
        <button type="button"
                onclick="location.href = "https://es.stackoverflow.com/<c:url value="/libro_listar"/>"">Cancelar</button>
</form:form>

Controlador

@RequestMapping(value = "/libro_registrar", method = RequestMethod.GET)
public String registrar_GET(Model model) {
    Libro libroModel = new Libro(); //libro vacío
    model.addAttribute("libro", libroModel);

    return "libro_registrar";
}

@RequestMapping(value = "/libro_registrar", method = RequestMethod.POST)
public String registrar_POST(Libro libro) //vuelo cargado
{
    //se utiliza el servicio guardar
    libroService.insert(libro);

    //redireccionar al value "/libro_listar"
    return "redirect:/libro_listar";
}

Espero me puedan ayudar por favor. Y si pueden comentarme solamente como se haría con tablas que tienen relacion N:M ? gracias

Normalization of database tables. Spring DATA JPA Hibernate

I created the table as stated in the hibernate Bidirectional @ManyToMany documentation. I did exactly the same as shown.

When I add a person, I get the following table:

enter image description here

If you look closely, you will notice that there is a violation of one of the main principles of normalization, that is, information redundancy. Repeats several times New York and Los Angeles

How to add a person correctly so as not to violate the normalization of the database tables, so that there is no data redundancy?

enter image description here

Person.java

    @Entity(name = "Person")
    public class Person {

        @Id
        @GeneratedValue
        private Long id;

        private String name;

        @ManyToMany(cascade = {CascadeType.PERSIST, CascadeType.MERGE})
        private List<Address> addresses = new ArrayList<>();

        public Person() {
        }

        public Person(String name) {
            this.name = name;
        }

        // Getters and setters are omitted for brevity

        public void addAddress(Address address) {
            addresses.add( address );
            address.getOwners().add( this );
        }

        public void removeAddress(Address address) {
            addresses.remove( address );
            address.getOwners().remove( this );
        }
    }

Address.java

    @Entity(name = "Address")
    public class Address {

        @Id
        @GeneratedValue
        private Long id;

        private String street;

        @ManyToMany(mappedBy = "addresses")
        private List<Person> owners = new ArrayList<>();

        public Address() {
        }

        public Address(String street) {
            this.street = street;
        }

        // Getters and setters are omitted for brevity
    }

LifecycleController.java

    @Controller
    public class LifecycleController {

        @Autowired
        ServiceJpa serviceJpa;


        @GetMapping(value = "/savePerson")
        public String savePersonAddress () {


            Person person1 = new Person("Jack");

            Address address1 = new Address( "New York" );
            Address address2 = new Address( "Los Angeles" );

            person1.addAddress( address1 );
            person1.addAddress( address2 );

            serviceJpa.savPerson( person1 );


            return "/savePerson";
        }

    }

java – Hibernate SQL statement did not print in separate file as mentioned in logback

This is a web application. Below is my logback.xml

<?xml version="1.0" encoding="UTF-8"?>
<configuration scan="true" scanPeriod="30 seconds">

    <property name="LOGS" value="/mnt/opt/logs/wls_12c"/>

    <contextListener class="ch.qos.logback.classic.jul.LevelChangePropagator">
        <resetJUL>true</resetJUL>
    </contextListener>

    <!--To enable JMX Management  -->
    <jmxConfigurator/>

    <appender name="FILE" class="ch.qos.logback.core.FileAppender">
        <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
            <!-- Hourly rollover -->
            <fileNamePattern>${LOGS}/sql.log.%d{yyyyMMdd.HH}hr.%i.gz</fileNamePattern>
            <maxHistory>1440</maxHistory>
            <totalSizeCap>10GB</totalSizeCap>
            <maxFileSize>500MB</maxFileSize>

        </rollingPolicy>
        <encoder>
            <pattern>
                <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
            </pattern>
        </encoder>
    </appender>

    <logger name="org.hibernate.SQL" additivity="false">
        <level value="Debug"/>
        <appender-ref ref="FILE"/>
    </logger>

    <logger name="org.hibernate.type" additivity="false">
        <level value="Debug"/>
        <appender-ref ref="FILE"/>
    </logger>

    <root level="INFO">
        <appender-ref ref="FILE"/>
    </root>
</configuration>

The hibernate sql statement did not print into my log file even in my persistance.hibernate.properties hibernate.show_sql = false, while the others logs in the classes are printed to the log. Is my logback.xml contained any issues? How can I print the hibernate sql statement to the log file?

postgresql – Guardar entidad que tiene vinculada otras 2 entidades java spring hibernate

Estoy creando una api rest con Java Spring, estoy usando java-spring-data para el tema de persistencia. Al tratar de guardar un booking (que tiene asociado un member y un facility) me da error.

Me dice que:

org.postgresql.util.PSQLException: ERROR: el valor null para la columna «facid» viola la restricción not null
  Detail: La fila que falla contiene (7, 10, 2021-03-24 21:30:00, null, null).

El hibernate sql:

Hibernate: insert into bookings (slots, starttime) values (?, ?)

Incluso antes de hacer booking.save hice un systemout para ver que contenia:

Booking{bookingId=null, startTime=2021-03-24T21:30, slots=10, facility=Facility{facilityId=1, name='El conuco', memberCost=400.0, guestCost=500.3, initialOutlay=10000.0, monthlyMaintenance=100.0, bookings=()}, member=Member{memberId=1, surname='apellido', firstname='nombre', address='direccion', zipcode=6001, telephone='04248813351', recommendedBy=null, joinDate=2021-03-23T14:54:52.294, bookings=()}}

La parte donde hago el booking.save es en el servicio (el repositorio extiende CrudRepository), aqui:

@Override
    public BookingResponseDTO save(BookingRequestDTO dto) {
        Booking booking = new Booking();
        Optional<Member> member = memberRepository.findByID(dto.getMemid());
        Optional<Facility> facility = facilityRepository.findById(dto.getFacid());

        if (member.isPresent() && facility.isPresent()) {
            booking.setMember(member.get());
            booking.setFacility(facility.get());
            booking.setSlots(dto.getSlots());
            booking.setStartTime(dto.getStarttime());

            System.out.println(booking);

            booking = repository.save(booking); // Aqui lanza el error

            return BookingResponseDTO.toDTO(booking);
        } else {
            return null;
        }
    }

Modelo

Este es mi modelo en la base de datos

Esta es mi entidad members

@Entity
@Table(name = "members")
public class Member {
    public Member() {
    }

    public Member(String surname, String firstname, String address, Integer zipcode, String telephone, Member recommendedBy, LocalDateTime joinDate) {
        this.surname = surname;
        this.firstname = firstname;
        this.address = address;
        this.zipcode = zipcode;
        this.telephone = telephone;
        this.recommendedBy = recommendedBy;
        this.joinDate = joinDate;
    }

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "memid")
    private Integer memberId;

    @Column(name = "surname", nullable = false)
    private String surname;

    @Column(name = "firstname", nullable = false)
    private String firstname;

    @Column(name = "address", nullable = false)
    private String address;

    @Column(name = "zipcode", nullable = false)
    private Integer zipcode;

    @Column(name = "telephone", nullable = false)
    private String telephone;

    @ManyToOne(optional=true)
    @JoinColumn(name="recommendedby")
    private Member recommendedBy;

    @Column(name = "joindate", updatable = false, nullable = false)
    private LocalDateTime joinDate;

    @OneToMany(mappedBy = "member")
    private List<Booking> bookings;
    
    // getters y setters
}

Esta es mi entidad facility

@Entity
@Table(name = "facilities")
public class Facility {
    public Facility() {
    }

    public Facility(String name, Double memberCost, Double guestCost, Double initialOutlay, Double monthlyMaintenance) {
        this.name = name;
        this.memberCost = memberCost;
        this.guestCost = guestCost;
        this.initialOutlay = initialOutlay;
        this.monthlyMaintenance = monthlyMaintenance;
    }

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "facid")
    private Integer facilityId;

    @Column(name = "name", nullable = false)
    private String name;

    @Column(name = "membercost", nullable = false)
    private Double memberCost;

    @Column(name = "guestcost", nullable = false)
    private Double guestCost;

    @Column(name = "initialoutlay", nullable = false)
    private Double initialOutlay;

    @Column(name = "monthlymaintenance", nullable = false)
    private Double monthlyMaintenance;

    @OneToMany(mappedBy = "facility")
    private List<Booking> bookings;

    // getters y setters
}

Esta es mi entidad booking

@Entity
@Table(name = "bookings")
public class Booking {
    public Booking() {
    }

    public Booking(LocalDateTime startTime, Integer slots, Facility facility, Member member) {
        this.startTime = startTime;
        this.slots = slots;
        this.facility = facility;
        this.member = member;
    }

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "bookid")
    private Integer bookingId;

    @Column(name = "starttime", nullable = false)
    private LocalDateTime startTime;

    @Column(name = "slots", nullable = false)
    private Integer slots;

    @ManyToOne
    @JoinColumn(name = "facid", nullable = false, insertable = false, updatable = false)
    private Facility facility;

    @ManyToOne
    @JoinColumn(name = "memid", nullable = false, insertable = false, updatable = false)
    private Member member;

    // getters y setters
}

Para mas información aquí el repositorio: https://github.com/darioxlz/Bookings-spring

Hibernate file is too small; how do I fix it?

I upgraded my Mac to 16G of ram a few years ago. I just noticed that /var/vm/sleepimage is only 8G, which likely explains why I’ve never been able to get my Mac to hibernate.

How can I fix it? SIP isn’t letting me delete the file.

hibernate – Erro com o orphanRemoval

Estou tentando utilizar o orphanRemoval para o projeto de TCC e estou tendo problema, creio que seja de dependência.

 @ManyToMany(cascade = CascadeType.ALL, orphanRemoval = true)
 private List<ReadingTarget> readingTargets;

Erro

Dependências:

inserir a descrição da imagem aqui

O que pode estar errado?

Macbook is setup to hibernate immediately, but it hibernates after ~1hr delay both on AC & battery

I tried to change the settings to all sorts of scenarios, but the laptop just refuses to hibernate right away. I want it to bypass sleep/standby completely, and cut off power to RAM immediately (hibernate).

I tried setting sleepdelayhigh/low and autopoweroffdelay to 0, with standby and autopoweroff to 0. Didn’t work.

Then I changed standby and autopoweroff to 1, but with 0 delay seconds. Again, didn’t work.

Then I decided to change the delay to 60s. Didn’t work.

I also experimented with hibernate 3 and 25.

It goes into hibernate after about 1 hour and I don’t understand why it stays in sleep mode for so long.

Another problem that I have is I setup displaysleep to 5 mins with auto sleep to 30mins, but every time the display is switched off, it goes immediately to sleep. Insane! I had to go back to 15mins.

This is what I have right now, but like I said, it just doesn’t hibernate after 60s. Neither on battery nor on AC.

 standbydelaylow      60
 standby              1
 halfdim              1
 hibernatefile        /var/vm/sleepimage
 powernap             0
 gpuswitch            2
 disksleep            10
 standbydelayhigh     60
 sleep                15
 autopoweroffdelay    60
 hibernatemode        25
 autopoweroff         1
 ttyskeepawake        1
 displaysleep         15
 highstandbythreshold 50
 acwake               0
 lidwake              1
 

java – um simples projeto crud com jsf + hibernate, mas o meu update é o único que não consegui por para funcionar

Tentei de várias maneiras, mas nenhuma funcionou.

meu xhtml da tela onde eu clico no button e ele me leva para a pag atualizar. TO TENTANDO PELO BOTÃO “Edit”.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
    xmlns:ui="http://java.sun.com/jsf/facelets"
    xmlns:f="http://java.sun.com/jsf/core"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:pt="http://xmlns.jcp.org/jsf/passthrough"
    xmlns:opt="http://primefaces.prime.com.tr/optimus"
    xmlns:p="http://primefaces.org/ui">

<h:head>
    <link rel="stylesheet" href="https://pt.stackoverflow.com/css/style.css" type="text/css" media="all"></link>
    <f:metadata>
2.    <f:viewParam name="usuario" value="#{beanUsuario.usuario.id}" />
3.    <f:event type="preRenderView"
            listener="#{beanUsuario.editarUsuario}" />
4. </f:metadata>

</h:head>
<h:body>
    <ui:composition template="Template.xhtml">
        <ui:define name="corpo">
            <h:form>
                <h:inputHidden value="#{beanUsuario.usuario.id}" />
                <p:dataTable id="tabela-usuario" var="usuario"
                    value="#{beanUsuario.usuarios}">
                    <p:column headerText="Nome">
                        <h:outputText value="#{usuario.nome}" />
                    </p:column>

                    <p:column headerText="Email">
                        <h:outputText value="#{usuario.email}" />
                    </p:column>

                    <p:column headerText="Telefone">
                        <h:outputText value="#{usuario.telefone}" />
                    </p:column>

                    <p:column>
                        <p:commandButton value="Excluir"
                            action="#{beanUsuario.excluirUsuario(usuario)}">
                            <f:ajax render="@form" />
                        </p:commandButton>

                        <h:commandButton value="Edit"
                            action="#{beanUsuario.editarUsuario}" ajax="false">
                            <f:setPropertyActionListener target="#{beanUsuario.usuario}"
                                value="#{usuario}" />
                        </h:commandButton>
                    </p:column>


                </p:dataTable>
                <br />
                <p:linkButton outcome="menu.xhtml" value="Menu"
                    style="margin-left:20px;" />
                <p:linkButton outcome="login.xhtml" value="Sair"
                    style="margin-left:20px;" />
            </h:form>
        </ui:define>
    </ui:composition>
</h:body>
</html>

meu bean:

public void atualizarUsuario() {
    UsuarioDao dao = new UsuarioDao();
    dao.update(usuario);
}

public String editarUsuario() {
    UsuarioDao dao = new UsuarioDao();
    boolean teste = dao.validarId(usuario);
    
       if(teste == true && usuario!=null){
             this.usuario.setId(usuario.getId());
             this.usuario.setNome(usuario.getNome());
             this.usuario.setEmail(usuario.getEmail());
             this.usuario.setTelefone(usuario.getTelefone());
             this.usuario.setSenha(usuario.getSenha());
       }

       return "atualizar";
    }

Meu dao:

public void update(Usuario usuario) {
    
    EntityManager manager = new ConnectionFactory().getConnection();
    try {
        manager.getTransaction().begin();
        manager.merge(usuario);
        manager.getTransaction().commit();
    } catch (Exception e) {
        manager.getTransaction().rollback();
    } finally {
        manager.close();
    }
    
}

public boolean validarId(Usuario usuario) {
    EntityManager manager = new ConnectionFactory().getConnection();
    manager.getTransaction().begin();
    
    javax.persistence.Query query = manager.createQuery("select id from Usuario u where u.id = :pId");
    query.setParameter("pId", usuario.getId());
    /*
     * query.setParameter("pNome", usuario.getNome()); query.setParameter("pEmail",
     * usuario.getEmail()); query.setParameter("pTelefone", usuario.getTelefone());
     * query.setParameter("pSenha", usuario.getSenha());
     */
    boolean usuarioExiste = !query.getResultList().isEmpty();
    
    manager.getTransaction().commit();
    manager.close();
    
    return usuarioExiste;
}

minha pag atualizar:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
    xmlns:ui="http://java.sun.com/jsf/facelets"
    xmlns:f="http://java.sun.com/jsf/core"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:pt="http://xmlns.jcp.org/jsf/passthrough"
    xmlns:opt="http://primefaces.prime.com.tr/optimus"
    xmlns:p="http://primefaces.org/ui">
<h:head>
    <link rel="stylesheet" href="https://pt.stackoverflow.com/css/style.css" type="text/css" media="all"></link>
</h:head>
<ui:composition template="Template.xhtml">

    <ui:define name="corpo">
        <center>
            <h:outputLabel value="Atualizar" styleClass="titulo-cadastro" />
        </center>
        <h:body>
            <h:form>

                <h:panelGrid columns="2" cellpadding="4"
                    styleClass="panel-grid-cadastro">

                    <h:outputLabel for="nome" value="Nome: " />
                    <p:inputText id="nome" value="#{beanUsuario.usuario.nome}" />

                    <h:outputLabel for="email" value="Email: " />
                    <p:inputText id="email" value="#{beanUsuario.usuario.email}" />

                    <h:outputLabel for="telefone" value="Telefone: " />
                    <p:inputMask id="telefone" value="#{beanUsuario.usuario.telefone}"
                        mask="(99) 99999-9999" />

                    <h:outputLabel for="senha" value="Senha: " />
                    <p:password id="senha" value="#{beanUsuario.usuario.senha}" />

                    <h:commandButton value="Atualizar"
                        action="#{beanUsuario.atualizarUsuario}">

                        <f:ajax render="nome email telefone senha" execute="@form" />
                    </h:commandButton>
                </h:panelGrid>
            </h:form>
        </h:body>
    </ui:define>

</ui:composition>
</html>

Debuguei: ele não resgata o id do usuário que eu quero atualizar, vem o id=null:
inserir a descrição da imagem aqui