简体   繁体   English

带有Java Rest Web服务的手动DbConnection(球衣)

[英]Manual DbConnection with Java Rest Webservice (jersey)

I was wondering if anyone could help me with a small problem. 我想知道是否有人可以帮助我解决一个小问题。 I'm trying to create a restfull service in Java using Jersey. 我正在尝试使用Jersey创建Java的restfull服务。

But I cannot find any examples on how to make a manual db connections. 但是我找不到关于如何进行手动数据库连接的任何示例。 And If I do, the connection returns a nullpointer when querying the database. 而且,如果这样做,则在查询数据库时连接将返回空指针。

public DbConnection()
{
    try 
    {
        // This will load the MySQL driver, each DB has its own driver
        Class.forName("com.mysql.jdbc.Driver");
        // Setup the connection with the DB
        connection =     DriverManager.getConnection("jdbc:mysql://url/team_staging?"
                        + "user=X&password=X");
    }
    catch (ClassNotFoundException ex) 
    {
        Logger.getLogger(DbConnection.class.getName()).log(Level.SEVERE, null, ex);
    } 
    catch (SQLException ex) 
    {
        Logger.getLogger(DbConnection.class.getName()).log(Level.SEVERE, null, ex);
    }
}

Could someone point my in the right direction here? 有人可以在这里指出正确的方向吗? I don't want to use any ORM. 我不想使用任何ORM。

I find it hard to find good examples without hibernate or auto-generated rest service in netbeans... 我发现很难在netbeans中没有休眠或自动生成的REST服务的情况下找到好的示例。

My regards, Axl 我的问候,Axl

I think your instinct to steer clear of an ORM solution is a good one. 我认为您避免使用ORM解决方案的本能很好。

You're writing a web service, which means it's deployed on a servlet/JSP engine at a minimum (eg Tomcat) or a full Java EE app server. 您正在编写一个Web服务,这意味着它至少部署在Servlet / JSP引擎(例如Tomcat)或完整的Java EE应用服务器上。 I'd learn how to create a JNDI connection pool for your app server. 我将学习如何为您的应用服务器创建JNDI连接池。

You want to externalize your connection parameters (eg driver, URL, etc.) 您想外部化连接参数(例如驱动程序,URL等)

I don't see a class member for that connection. 我看不到该连接的班级成员。 What happens when you exit the ctor? 退出控制器时会发生什么? Is it out of scope? 是否超出范围? That would explain the NPE. 那将解释NPE。

I'd write it this way: 我会这样写:

package persistence;

public class DatabaseUtils {
    private DatabaseUtils() {}

    public static Connection getConnection(String driver, String url, String username, String password) throws Exception {
        Class.forName(driver);
        return DriverManager.getConnection(url, username, password);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM