我在过去的3个小时里到处都是,但仍然无法让它发挥作用。我需要能够连接1prefix和1suffix值,以形成一个由字符串和数字组成的id。
如何定义表格。
public class TestDatabase {
private DBI dbi;
private Handle handle;
private CarDAO carDAO;
@Before
public void setUpDatabase() throws Exception {
Environment environment = new Environment( "test-env", Jackson.newObjectMapper(), null, new MetricRegistry(), null );
dbi = new DBIFactory().build( environment, getDataSourceFactory(), "cardb" );
carDAO = dbi.onDemand(CarDAO.class);
handle = dbi.open();
}
protected DataSourceFactory getDataSourceFactory()
{
DataSourceFactory dataSourceFactory = new DataSourceFactory();
dataSourceFactory.setDriverClass( "com.mysql.jdbc.Driver" );
dataSourceFactory.setUrl( "jdbc:mysql://127.0.0.1:3306/cardb" );
dataSourceFactory.setUser( "root" );
dataSourceFactory.setPassword( "root" );
return dataSourceFactory;
}
@Test
public void testCreatecar(){
Car car = new Car("Test car","Test car teaser","http://localhost:8080/","#ff0000","car test description");
Long carId = carDAO.createCar(car);
assertNotNull(carId);
}
@Test
public void testCreatecar2(){
Car car = new Car("Test car","Test car teaser","http://localhost:8080/","#ff0000","car test description");
Long carId = carDAO.createCar2(car);
assertNotNull(carId);
}
}
我需要能够生成
DISC0001 DISC0002 DISC0003
只有数字自动递增每次插入到DiscounName。我只想在主键前加上" DISC"作为折扣标识符。
我正在使用Derby。如果您可以帮助我或提供替代解决方案,我将非常感谢。
感谢。
答案 0 :(得分:0)
生成的列应该完成这项工作。 我没有要测试的Derby,但是后续工作可以在DB2中运行
create table t4 (prefix varchar(20) not null with default 'DISC',
suffix int generated always as identity (start with 1 increment by 1),
id generated always as (prefix || (substr2('000' || suffix, -4, 4))) )
答案 1 :(得分:0)
另一种方法是使用SEQUENCE
和NEXT VALUE FOR
语法为主键生成新值,如下所示:http://db.apache.org/derby/docs/10.12/ref/rrefsqljnextvaluefor.html
例如,你可以这样做:
create sequence discount_ids start with 1;
insert into discounts (id, name)
values ( 'DISC' || cast( next value for discount_ids as char(20)),
'bubble gum' );