Postgres 与 Glassfish 连接池

发布于 2024-11-19 05:09:04 字数 539 浏览 1 评论 0 原文

我是 Java EE 世界的新手,希望在 Web 应用程序中使用 PostgreSQL 作为我的数据库。我使用 Glassfish 作为我的应用程序服务器,并通过管理界面添加了一个连接池(我使用了这个 网站 寻求帮助)。现在我不知道在我的应用程序中使用连接池的“正确”方法是什么(事实上我目前不知道如何从池中获取连接并编写一个简单的查询)。

我们需要编写非常复杂的查询,所以我不知道是否应该为每个表创建一个映射并使用映射,或者只使用sql和某种行映射器来解析结果(我们之前使用过Spring RowMapper) 。

所以我的问题是:

  1. 使用池中的连接有哪些不同的方法?
  2. 这些模式的优点(缺点)是什么?
  3. 如何创建可以处理复杂且性能密集型查询的巧妙映射。
  4. 这与 Hibernate 一起工作吗?如果是这样,怎么办?

I am new to the Java EE World and want to use PostgreSQL as my database in an web application. I use Glassfish as my application server and added a connection pool via the administration interface (I used this site for help). Now I don't know what is the "right" way to use the connection pool in my application (in fact I currently don't know how to even get an connection from the pool and write a simple query).

We need to write pretty complex queries, so I don't know if I should create a mapping for every table and use the mappings, or just use sql and some kind of row mapper to pars the results (we used the Spring RowMapper before).

So my Question are:

  1. What different ways are there to use the connections from the pool?
  2. What are the (dis)advantages of these patterns?
  3. How to create a clever mapping that can handle complicated and performance intensive query's.
  4. Does this work with Hibernate? And if so, how?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

分分钟 2024-11-26 05:09:04

1 - 如果您的连接池是使用 glassfish 配置的,您可以开发一个简单的 EJB 并使用注释注入连接,我认为这是处理池中连接的最佳方法。

(所有示例都与 hibernate 兼容,并且在 postgresql 数据库上运行良好)

例如:

@Stateless
public class myEjb
{
    // inject the entityManager  
    @PersistenceContext(unitName = "myPu")
    private EntityManager em;

    public Car findCarById(Long carId)
    {
        Car aCar = (Car) em.find(Car.class, carId);
        return aCar;
    }
}

unitName“myPu”是在 glassfish 管理控制台中配置的 JDBC 资源的 JNDI 名称。

2 - 这种模式的优点是它不依赖于代码,您不能更改有关开发、测试或生产环境的 JDBC 资源。 JDBC url、用户和密码是在服务器上配置的,而不是在 XML 文件中配置的,每次从一个环境切换到另一个环境时,您都可以仔细更改该文件。这样您就不必处理事务,这是在异常时提交或回滚的服务器。
如果您需要自己处理事务,您可以在无状态注释下添加注释:

@TransactionManagement(value=TransactionManagementType.BEAN) 

您需要自己处理事务,例如:

em.getTransaction().begin();
try
{
    // do something with the entityManager
    em.getTransaction().commit();
}
catch(MyException ex)
{
    em.getTransaction().rollback();
}

3 - 如果您需要创建复杂的请求,您可以在实体上声明一些命名查询。
下面是 Car 实体的可能实现:

@Entity
public class Car 
{
    @NamedQueries(
    {
        @NamedQuery(name = "Car.findByBrandAndColor", query = "SELECT c FROM Car WHERE c.brand = :brand AND color = :color")
    })
}

下面是添加到使用先前命名查询的 EJB 的函数示例:

public List<Car> findAllCarByBrandAndColor(String aBrand, String aColor)
{
    List<Car> theCars;

    Query theQuery = em.createNamedQuery("Car.findByBrandAndColor");
    theQuery.setParameter("brand", aBrand);
    theQuery.setParameter("color", aColor);

    try
    {
        theCars = (List<Car>) query.getResultList();
    }
    catch(NoResultException ex)
    {
        theCars = null;
    }

    return theCars;
}

当然,您可以根据需要编写复杂的命名查询(命名查询会被缓存,并且可能会提高性能) ),但如果你确实需要直接查询数据库,你可以使用原生查询,如下所示:

// the query is native SQL
Query theQuery = em.createNativeQuery("SELECT * FROM car WHERE color = 'blue' AND brand = 'toyota'", Car.class);
Car aCar = (Car) query.getSingleResult();

1 - If your connection pool is configured using glassfish, you may develop a simple EJB and inject the connection using annotation, I think this is the best way to handle connexion from your pool.

(All examples are compatible with hibernate and work well on postgresql database)

eg:

@Stateless
public class myEjb
{
    // inject the entityManager  
    @PersistenceContext(unitName = "myPu")
    private EntityManager em;

    public Car findCarById(Long carId)
    {
        Car aCar = (Car) em.find(Car.class, carId);
        return aCar;
    }
}

the unitName "myPu" is the JNDI name of your JDBC resource configured in the glassfish administration console.

2 - the advantage of this pattern is that it is not code dependant, you may not change your JDBC ressource regarding the dev, test or production environment. The JDBC url, user and pass are configured on the server and not in an XML file that you may carefully change each time you switch from an environment to another. This way you don't have to handle the transaction, this is the server that commit or rollback on exception.
If you need to handle the transaction yourself, you may add the annotation under the Stateless one:

@TransactionManagement(value=TransactionManagementType.BEAN) 

you the need to handle by yourself the transaction like:

em.getTransaction().begin();
try
{
    // do something with the entityManager
    em.getTransaction().commit();
}
catch(MyException ex)
{
    em.getTransaction().rollback();
}

3 - If you need to create complexe request, you may declare some named queries on your entity.
below a possible implementation of the Car entity:

@Entity
public class Car 
{
    @NamedQueries(
    {
        @NamedQuery(name = "Car.findByBrandAndColor", query = "SELECT c FROM Car WHERE c.brand = :brand AND color = :color")
    })
}

below an example of function to add to your EJB that use the previous named query:

public List<Car> findAllCarByBrandAndColor(String aBrand, String aColor)
{
    List<Car> theCars;

    Query theQuery = em.createNamedQuery("Car.findByBrandAndColor");
    theQuery.setParameter("brand", aBrand);
    theQuery.setParameter("color", aColor);

    try
    {
        theCars = (List<Car>) query.getResultList();
    }
    catch(NoResultException ex)
    {
        theCars = null;
    }

    return theCars;
}

Of course, you can write named queries as complex as you want (named queries are cached and may be better for performance), but if you really need to query directly the database, you may use native queries as below:

// the query is native SQL
Query theQuery = em.createNativeQuery("SELECT * FROM car WHERE color = 'blue' AND brand = 'toyota'", Car.class);
Car aCar = (Car) query.getSingleResult();
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文