> For the complete documentation index, see [llms.txt](https://avbravo-2.gitbook.io/trucosjakartaee/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://avbravo-2.gitbook.io/trucosjakartaee/overview/mezclar-dos-proyectos-ejb/agregar-campos-autoincrementables-renombrar-campos.md).

# Agregar campos autoincrementables, renombrar  campos

## Objetivo

* Cambiar el campo idarticulo que es un String combinado, por un campo Integer autoincrementable.
* Actualizar los entitys Referenciados con el nuevo valor.
* Cambiar el nombre del atributo actual idarticulo que es String por el nombre de código.

## Imaginemos que contamos con tres colecciones.

| **Coleccion** |   |
| ------------- | - |
| Articulo      |   |
| Ordendetalle  |   |
| Inventario    |   |

![](/files/-Lc1X82M21Ja-y1le6Oc)

## Pasos:

* Agregar en los entity el atributo **numero** en las tres colecciones(Articulo, Inventario, Ordendetalle. Facturadetalle)
* En Articulo usar un método que actualice con un autoincrementable el valor del nuevo campo **numero**
* Recorrer la coleccion de Inventario y actualizar el campo **numero** con el valor correspondiente del articulo comparando por idarticulo de ambas colecciones.
* Recorrer la coleccion de Ordendetalle y actualizar el campo **numero** con el valor correspondiente del articulo comparando por idarticulo de ambas colecciones.
* Renombrar el campo **idarticulo** en Articulo con el nombre de **codigo**.
* Renombrar el campo numero por idarticulo en Articulo
* Eliminar el campo idarticulo en Inventario
* Renombrar el campo numero por idarticulo en Inventario
* Eliminar el campo idarticulo en Ordendetalle
* Renombrar el campo numero por idarticulo en Ordendetalle
* En los entitys @Referenced cambiar el javatype="String" por javatype="Integer"

```java
@Referenced(documment = "Articulo",
repository = "com.avbravo.storeejb.repository.ArticuloRepository",
field = "idarticulo", javatype = "String", lazy = false)
```

Por

```java
@Referenced(documment = "Articulo",
repository = "com.avbravo.storeejb.repository.ArticuloRepository",
field = "idarticulo", javatype = "Integer", lazy = false)
```

## Entitys

```java
public class Articulo {

    @Id
    private String idarticulo;
    private String descripcion;
    @Referenced(documment = "Grupoarticulo",
            repository = "com.avbravo.storeejb.repository.GrupoarticuloRepository",
            field = "idgrupoarticulo", javatype = "Integer", lazy = false)
    private Grupoarticulo grupoarticulo;
    @Referenced(documment = "Proveedor",
            repository = "com.avbravo.storeejb.repository.ProveedorRepository",
            field = "idproveedor", javatype = "String", lazy = false)
    private Proveedor proveedor;

    @Referenced(documment = "Modelo",
            repository = "com.avbravo.storeejb.repository.ModeloRepository",
            field = "idmodelo", javatype = "Integer", lazy = false)
    private Modelo modelo;

    @Referenced(documment = "Tamano",
            repository = "com.avbravo.storeejb.repository.TamanoRepository",
            field = "idtamano", javatype = "Integer", lazy = false)
    private Tamano tamano;

    @Referenced(documment = "Color",
            repository = "com.avbravo.storeejb.repository.ColorRepository",
            field = "idcolor", javatype = "String", lazy = false)
    private Color color;

    @Referenced(documment = "Bodega",
            repository = "com.avbravo.storeejb.repository.BodegaRepository",
            field = "idbodega", javatype = "String", lazy = false)
    private Bodega bodega;

    private Double costo;
    private Double precioventapublico;
    private Double precioventacredito;

    private Integer cantidad;
    private Integer reorden;


    private String activo;


    @Embedded
    private List<UserInfo> userInfo;

    public Articulo() {
    }

}

public class Inventario {
    @Id
    private Integer idinventario;
    @Referenced(documment = "Articulo",
            repository = "com.avbravo.storeejb.repository.ArticuloRepository",
            field = "idarticulo", javatype = "String", lazy = false)
    private Articulo articulo;
    private String id;
    private String tipoid;
    private Integer cantidad;


      @Embedded
    private List<UserInfo> userInfo;

}


public class Ordendetalle {

    @Id
    private Integer idordendetalle;


    @Referenced(documment = "Orden", repository = "com.avbravo.storeejb.repository.OrdenRepository",
            field = "idorden", javatype = "Integer", lazy = false)
    private Orden orden;
    @Referenced(documment = "Articulo", repository = "com.avbravo.storeejb.repository.ArticuloRepository",
            field = "idarticulo", javatype = "String", lazy = false)
    private Articulo articulo;

    private Integer cantidadanterioremisor;
    private Integer cantidadanteriorreceptor;
    private Integer cantidad;

    @Embedded
    private List<UserInfo> userInfo;


    public Ordendetalle() {
    }

}
```

### 1.Agregamos el atributo numero a los  entitys (Articulo, Inventario,Ordendetalle,Facturadetalle)

```java
   private Integer numero;
```

![](/files/-Lc1X82SzcZozggBblIw)

## 2. Ejecutar el Método

![](/files/-Lc1X82U6DpOrlcguldB)

Genera el numero en Articulo y actualiza el campo numero con el correspondiente al articulo en Ordendetalle, Inventario.

```java
   public String generarNumeros() {
        try {
            List<Articulo> list = new ArrayList<>();
            list = articuloRepository.findAll();
            for (Articulo a : list) {
                Integer id = autoincrementableStoreejbServices.getContador("articulo");
                a.setNumero(id);
                articuloRepository.update(a);
            }


            //Actulizar Inventario
            List<Inventario> listInventario = inventarioRepository.findAll();
            listInventario.forEach((i) -> {
                List<Articulo> articuloList = articuloRepository.findBy("idarticulo",i.getArticulo().getIdArticulo());
                if (!articuloList.isEmpty()) {
                    i.setNumero(articuloList.get(0).getNumero());
                    inventarioRepository.update(i);
                }
            });
          //Actulizar Ordendetalle
          List<Ordendetalle> listOrdendetalle=ordendetalleRepository.findAll();
          listOrdendetalle.forEach((o) -> {
              List<Articulo> articuloList = articuloRepository.findBy("idarticulo",o.getArticulo().getIdArticulo());
                if (!articuloList.isEmpty()) {
                    o.setNumero(articuloList.get(0).getNumero());
                    ordendetalleRepository.update(o);
                }
            });

            JsfUtil.successMessage("Se generaron los numeros y se actualizaron ");

        } catch (Exception e) {
            JsfUtil.errorMessage("generarNumeros()" + e.getLocalizedMessage());
        }
        return "";
    }
```

### 3. Renombrar el atributo idarticulo por codigo en Articulo

```
db.articulo.updateMany({ }, {$rename:{"idarticulo":"codigo"}})
```

### 4. Renombrar numero por idarticulo en Articulo

```
db.articulo.updateMany({ }, {$rename:{"numero":"idarticulo"}})
```

### 5. Eliminar el atributo articulo.idarticulo de Inventario

```java
db.inventario.update({}, {$unset: {"articulo": 1}}, {multi: true})
```

### 6. Eliminar el atributo articulo.idarticulo de Ordendetalle

```java
db.ordendetalle.update({}, {$unset: {"articulo": 1}}, {multi: true})
```

### 7. Renombrar numero por idarticulo en Inventario

```
db.inventario.updateMany({ }, {$rename:{"numero":"articulo.idarticulo"}})
```

### 8. Renombrar numero por idarticulo en Inventario

```
db.ordendetalle.updateMany({ }, {$rename:{"numero":"articulo.idarticulo"}})
```

## 9. Cambiar el @Referenced(type="String"... en Inventario

por

@Referenced(type="Integer"...

## 10. Cambiar el @Referenced(type="String"... en Ordendetalle

por

@Referenced(type="Integer"...


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://avbravo-2.gitbook.io/trucosjakartaee/overview/mezclar-dos-proyectos-ejb/agregar-campos-autoincrementables-renombrar-campos.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
