Brooke  Giles

Brooke Giles

1548915523

JAVA JPA - Regular solution to persist all objects in project

I'm working on a backend which creates new user, news, various data etc.

So far I could create and persist a new User in the database. I think there will be many further entities also with relations. At this point I only see two way to persist the data:

  • create CreateXY, UpdateXY and DeleteXY classes
  • or code the persist method in each entity object

I think that is quiet redundant to write the persists again and again. Is there a nice way to go to persist objects in a nice way?

Main.java

package database;

import java.util.logging.Level;
import java.util.logging.Logger;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;

import backend.User;

public class Main {
private static final Logger LOGGER = Logger.getLogger(“JPA”);

public static void main(String[] args) {
    Main main = new Main();
    main.run();
}

public void run() {
    EntityManagerFactory factory = null;
    EntityManager entityManager = null;
    try {
        System.out.println("START");
        factory = Persistence.createEntityManagerFactory("shareiffUnit");
        System.out.println("END");
        entityManager = factory.createEntityManager();
        persistPerson(entityManager);
    } catch (Exception e) {
        LOGGER.log(Level.SEVERE, e.getMessage(), e);
        e.printStackTrace();
    } finally {
        if (entityManager != null) {
            entityManager.close();
        }
        if (factory != null) {
            factory.close();
        }
    }
}

private void persistPerson(EntityManager entityManager) {
    EntityTransaction transaction = entityManager.getTransaction();
    try {
        transaction.begin();
        User person = new User();
        person.setName("Homer");
        person.setPassword("Simpson");
        entityManager.persist(person);
        transaction.commit();
    } catch (Exception e) {
        if (transaction.isActive()) {
            transaction.rollback();
        }
    }
}

}

User.java

package backend;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table
public class User {

@Id
@GeneratedValue
private int id;
private String name;
private String password;
private Boolean isActive = false;


public int getId() {
    return id;
}
public void setId(int id) {
    this.id = id;
}
public String getName() {
    return name;
}
public void setName(String name) {
    this.name = name;
}
public String getPassword() {
    return password;
}
public void setPassword(String password) {
    this.password = password;
}
public Boolean isActive() {
    return isActive;
}
public void setActive(boolean isActive) {
    this.isActive = isActive;
}

}


#java #hibernate #jpa

What is GEEK

Buddha Community

I tend to have a set of manager-like classes along with a base for each manager class. The base is something like:

public class SomeBaseWritableDAO<T> {
    @PersistenceContext
    private EntityManager entityManager;

    protected EntityManager getEntityManager() {
        return entityManager;
    }

    public void save(T entity) {
        getEntityManager().persist(entity);
    }

    public T update(T entity) {
        return getEntityManager().merge(entity);
    }

    public void delete(T entity) {
        getEntityManager().remove(entity);
    }
}

That takes care of any @Entity type. Then, if I need more than the basic CRUD operations I’ll create a class specific manager:

public class SpecificDAO extends SomeBaseWritableDAO<SpecificEntity> {

    public SpecificEntity findBySomeCode(String inviteCode) {
        final String queryString = "select model from SomeEntity model " +
                "where model.code= :inviteCode";

        Query query = getEntityManager().createQuery(queryString);
        query.setParameter("inviteCode", inviteCode);

        try {
            return (SomeEntity) (query.getSingleResult());
        }
        catch( NoResultException nre ) {
            return null;
        }
    }
}

There are other ways to do this but this pattern has worked well in the past. If you’ve got a properly designed database with referential integrity then a good reverse engineering tool like the one in Eclipse or IntelliJ can generate your one to one and one to many relationships.

Arvel  Parker

Arvel Parker

1591611780

How to Find Ulimit For user on Linux

How can I find the correct ulimit values for a user account or process on Linux systems?

For proper operation, we must ensure that the correct ulimit values set after installing various software. The Linux system provides means of restricting the number of resources that can be used. Limits set for each Linux user account. However, system limits are applied separately to each process that is running for that user too. For example, if certain thresholds are too low, the system might not be able to server web pages using Nginx/Apache or PHP/Python app. System resource limits viewed or set with the NA command. Let us see how to use the ulimit that provides control over the resources available to the shell and processes.

#[object object] #[object object] #[object object] #[object object] #[object object] #[object object] #[object object] #[object object] #[object object] #[object object]

MEAN Stack Tutorial MongoDB ExpressJS AngularJS NodeJS

We are going to build a full stack Todo App using the MEAN (MongoDB, ExpressJS, AngularJS and NodeJS). This is the last part of three-post series tutorial.

MEAN Stack tutorial series:

AngularJS tutorial for beginners (Part I)
Creating RESTful APIs with NodeJS and MongoDB Tutorial (Part II)
MEAN Stack Tutorial: MongoDB, ExpressJS, AngularJS and NodeJS (Part III) 👈 you are here
Before completing the app, let’s cover some background about the this stack. If you rather jump to the hands-on part click here to get started.

#[object object] #[object object] #[object object] #[object object] #[object object] #[object object] #[object object] #[object object]

systemctl List All Failed Units/Services on Linux

Is there is a command to print list all failed units or services when using systemd on Linux? Can you tell me the systemctl command to list all failed services on Linux?

This quick tutorial explains how to find/list all failed systemd services/units on Linux operating systems using the systemctl command.

#[object object] #[object object] #[object object] #[object object] #[object object] #[object object] #[object object]

Tyrique  Littel

Tyrique Littel

1597723200

FreeBSD s3cmd failed [SSL CERTIFICATE_VERIFY_FAILED]

When I install s3cmd package on my FreeBSD system and try to use the s3cmd command I get the following error:

_ERROR: Test failed: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (ssl.c:1091)

How do I fix this problem on FreeBSD Unix system?

Amazon Simple Storage Service (s3 ) is object storage through a web service interface or API. You can store all sorts of files. FreeBSD is free and open-source operating systems. s3cmd is a command-line utility for the Unix-like system to upload, download files to AWS S3 service from the command line.

ERROR: Test failed: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed error and solution

This error indicates that you don’t have packages correctly installed, especially SSL certificates. Let us see how to fix this problem and install s3cmd correctly on FreeBSD to get rid of the problem.

How to install s3cmd on FreeBSD

Search for s3cmd package:

$ pkg search s3cmd

Execute the following command and make sure you install Python 3.x package as Python 2 will be removed after 2020:

$ sudo pkg install py37-s3cmd-2.1.0

Updating FreeBSD repository catalogue...
FreeBSD repository is up to date.
All repositories are up to date.
Checking integrity... done (0 conflicting)
The following 8 package(s) will be affected (of 0 checked):

New packages to be INSTALLED:
	libffi: 3.2.1_3
	py37-dateutil: 2.8.1
	py37-magic: 5.38
	py37-s3cmd: 2.1.0
	py37-setuptools: 44.0.0
	py37-six: 1.14.0
	python37: 3.7.8
	readline: 8.0.4

Number of packages to be installed: 8

The process will require 118 MiB more space.

Proceed with this action? [y/N]: y
[rsnapshot] [1/8] Installing readline-8.0.4...
[rsnapshot] [1/8] Extracting readline-8.0.4: 100%
[rsnapshot] [2/8] Installing libffi-3.2.1_3...
....
..
[rsnapshot] [8/8] Extracting py37-s3cmd-2.1.0: 100%
=====
Message from python37-3.7.8:

--
Note that some standard Python modules are provided as separate ports
as they require additional dependencies. They are available as:

py37-gdbm       databases/py-gdbm@py37
py37-sqlite3    databases/py-sqlite3@py37
py37-tkinter    x11-toolkits/py-tkinter@py37

#[object object] #[object object] #[object object] #[object object] #[object object] #[object object] #[object object]

Yoshiko  Jones

Yoshiko Jones

1598195340

How to configure AWS SES with Postfix MTA

How do I configure Amazon SES With Postfix mail server to send email under a CentOS/RHEL/Fedora/Ubuntu/Debian Linux server?

Amazon Simple Email Service (SES) is a hosted email service for you to send and receive email using your email addresses and domains. Typically SES used for sending bulk email or routing emails without hosting MTA. We can use Perl/Python/PHP APIs to send an email via SES. Another option is to configure Linux or Unix box running Postfix to route all outgoing emails via SES.

  • » Remove sendmail
  • » Install postfix
  • » Configuring postfix for SES
  • » Test postfix

Procedure to configure AWS SES with Postfix

Before getting started with Amazon SES and Postfix, you need to sign up for AWS, including SES. You need to verify your email address and other settings. Make sure you create a user for SES access and download credentials too.

Step 1 – Uninstall Sendmail if installed

If sendmail installed remove it. Debian/Ubuntu Linux user type the following apt command/apt-get command:

$`` sudo apt --purge remove sendmail

CentOS/RHEL user type the following yum command or dnf command on Fedora/CentOS/RHEL 8.x:

$`` sudo yum remove sendmail

$`` sudo dnf remove sendmail

Sample outputs from CentOS 8 server:

Dependencies resolved.
===============================================================================
 Package           Architecture  Version               Repository         Size
===============================================================================
Removing:
 sendmail          x86_64        8.15.2-32.el8         @AppStream        2.4 M
Removing unused dependencies:
 cyrus-sasl        x86_64        2.1.27-1.el8          @BaseOS           160 k
 procmail          x86_64        3.22-47.el8           @AppStream        369 k

Transaction Summary
===============================================================================
Remove  3 Packages

Freed space: 2.9 M
Is this ok [y/N]: y

#[object object] #[object object] #[object object] #[object object] #[object object] #[object object] #[object object]