如何使用命名查询在hibernate中获取当前数据库名称。
我试过这样,
String q1 = "select database()";
Query query1 = em.createQuery(q1);
String dbName = (String)query1.getResultList().get(0);
System.out.println("database name: "+dbName);
但这会抛出这样的错误,
HTTP ERROR 500
Problem accessing /admin/user. Reason:
No data type for node: org.hibernate.hql.internal.ast.tree.MethodNode
\-[METHOD_CALL] MethodNode: '('
+-[METHOD_NAME] IdentNode: 'database' {originalText=database}
\-[EXPR_LIST] SqlNode: 'exprList'
Caused by:
java.lang.IllegalStateException: No data type for node: org.hibernate.hql.internal.ast.tree.MethodNode
\-[METHOD_CALL] MethodNode: '('
+-[METHOD_NAME] IdentNode: 'database' {originalText=database}
\-[EXPR_LIST] SqlNode: 'exprList'
但是,如果我在Sql GUI控制台中运行相同的查询,则会显示当前的数据库名称。
答案 0 :(得分:0)
你可以试试这个
sessionFactory.getSettings().getConnectionProvider().getConnection().getMetaData().getURL();
答案 1 :(得分:0)
请参见,查询使用的是postgres,在其他数据库方言中可能有所不同。我之所以使用,是因为我不确定是否已连接到正确的数据库。
在rs.getString(1)中:我写了“ 1”,因为postgres仅返回1列。如果结果没有给出数据库名称,则可以使用for并打印所有列(package com.mygdx.game.mytile;
import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.assets.AssetManager;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.maps.MapProperties;
import com.badlogic.gdx.maps.tiled.TiledMap;
import com.badlogic.gdx.maps.tiled.TiledMapRenderer;
import com.badlogic.gdx.maps.tiled.TmxMapLoader;
import com.badlogic.gdx.maps.tiled.renderers.OrthogonalTiledMapRenderer;
public class TileTest extends ApplicationAdapter {
private TiledMap map;
private TiledMapRenderer renderer;
private OrthographicCamera camera;
private AssetManager manager;
private Integer tileWidth;
private Integer tileHeight;
private Integer mapWidthInTiles;
private Integer mapHeightInTiles;
private int mapWidthInPixels;
private int mapHeightInPixels;
@Override
public void create () {
manager = new AssetManager();
manager.setLoader(TiledMap.class, new TmxMapLoader());
manager.load("level_1_better.tmx", TiledMap.class);
manager.finishLoading();
map = manager.get("level_1_better.tmx", TiledMap.class);
MapProperties properties = map.getProperties();
tileWidth = properties.get("tilewidth", Integer.class);
tileHeight = properties.get("tileheight", Integer.class);
mapWidthInTiles = properties.get("width", Integer.class);
mapHeightInTiles = properties.get("height", Integer.class);
mapWidthInPixels = mapWidthInTiles * tileWidth;
mapHeightInPixels = mapHeightInTiles * tileHeight;
camera = new OrthographicCamera(320.f, 180.f);
camera.position.x = mapWidthInPixels * .5f;
camera.position.y = mapHeightInPixels * .35f;
renderer = new OrthogonalTiledMapRenderer(map);
}
@Override
public void render () {
Gdx.gl.glClearColor(.5f, .7f, .9f, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
camera.update();
renderer.setView(camera);
renderer.render();
}
@Override
public void dispose () {
manager.dispose();
}
}
),不仅像我一样打印第1列。
for i=1 i<columnNumber; i++){print: rs.getString(i)}